2017-06-27 28 views

回答

0

strsplit()將會把字符串轉換成字符的載體:

> x=strsplit(x, split=" ")[[1]] 
[1] "1:A" "2:A" "3:A" "5:A" "7:A" "8:A" "9:A" 

從那裏,你可以得到原始數據爲字符:

> x=gsub(":A", "", x) 
[1] "1" "2" "3" "5" "7" "8" "9" 

然後,您可以轉換爲數字和子集他們,但是你想要的。

2
#Get the numeric values only 
temp = as.integer(unlist(strsplit(gsub(":A", "", x), " "))) 

#Split temp into chunks of consecutive integers 
#Get range for each chunk and paste them together 
#Paste :A at the end 
sapply(split(temp, cumsum(c(TRUE, diff(temp) != 1))), function(x) 
    paste(paste(unique(range(x)), collapse = "-"), ":A", sep = "")) 
#  1  2  3 
#"1-3:A" "5:A" "7-9:A" 
相關問題