如何从R中的字符串中将连续的整数分组?

时间:2017-06-27 19:12:15

标签: r string

所以,让我说我有这个字符串

x <- "1:A 2:A 3:A 5:A 7:A 8:A 9:A"

R中是否有一个函数允许我准备这个字符串的部分,以便输出:

[1] 1-3:A 5:A 7-9:A

2 个答案:

答案 0 :(得分: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" 

答案 1 :(得分: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"

然后你可以根据需要转换为数字和子集。