假设我有这个字符串
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发布于 2017-06-28 03:28:41
#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" 发布于 2017-06-28 03:17:51
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"然后,您可以将其转换为数字,并随心所欲地对其进行子集。
https://stackoverflow.com/questions/44788101
复制相似问题