我有一个由“Y”和“N”组成的向量x。
> x
[1] Y N N N N N N N N N N Y N N N N
我想把它分成
> x1
[1] Y N N N N N N N N N N
和
> x2
[1] Y N N N N
这些向量总是以“Y”开头,并在下一个“Y”之前接收所有“N”。关于如何做到这一点的建议?
答案 0 :(得分:7)
您可以使用cumsum
和split
的组合来执行此操作:
x <- c("Y","N","N","N","N","N","N","N","N","N","N","Y","N","N","N","N")
v <- split(x,paste("x",cumsum(x=="Y"),sep=""))
答案 1 :(得分:3)
肯定有更好的方法,但是:
tst<-c("Y", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "Y", "N", "N", "N", "N")
starts<-which(tst=="Y") #where are the "Y"
ends<-c(starts[-1]-1, length(tst)) #pos before each "Y""
lapply(seq_along(starts), function(i){tst[(starts[i]):(ends[i])]}) #parts from each start till each end
答案 2 :(得分:3)
折叠成一个字符串,然后拆分为“Y”。
x <- c("Y", "N", "N", "N", "N", "N", "N", "N", "N", "N", "N", "Y", "N", "N", "N", "N")
y <- paste(x, collapse = "")
z <- paste("Y", strsplit(pn, "Y")[[1]], sep = "")[-1]
z
或使用行程编码。
n <- rle(x)$lengths[c(FALSE, TRUE)]
lapply(n, function(i) paste("Y", rep.int("N", i), sep = "", collapse = ""))
(这会给你一个列表而不是一个向量。如果这不是你想要的,请使用unlist
。)