我想将一个向量分成一个向量列表.生成的向量将具有可变长度,并且我需要仅在满足某些条件时才进行拆分.
样本数据:
set.seed(3)
x <- sample(0:9,100,repl=TRUE)
Run Code Online (Sandbox Code Playgroud)
例如,在这种情况下,我想x在每个0处拆分上面的向量.
目前我用自己的功能做到这一点:
ConditionalSplit <- function(myvec, splitfun) {
newlist <- list()
splits <- which(splitfun(x))
if (splits == integer(0)) return(list(myvec))
if (splits[1] != 1) newlist[[1]] <- myvec[1:(splits[1]-1)]
i <- 1
imax <- length(splits)
while (i < imax) {
curstart <- splits[i]
curend <- splits[i+1]
if (curstart != curend - 1)
newlist <- c(newlist, list(myvec[curstart:(curend-1)]))
i <- i + 1
}
newlist <- c(newlist, list(myvec[splits[i]:length(vector)]))
return(newlist)
}
Run Code Online (Sandbox Code Playgroud)
这个函数给出了我喜欢的输出,但我确信这比我的更好.
> MySplit <- function(x) x == 0
> ConditionalSplit(x, MySplit)
[[1]]
[1] 1 8 3 3 6 6 1 2 5 6 5 5 5 5 8 8 1 7 8 2 2
[[2]]
[1] 0 1
[[3]]
[1] 0 2 7 5 9 5 7 3 3 1 4 2 3 8 2 5 2 2 7 1 5 4 2
...
Run Code Online (Sandbox Code Playgroud)
以下行似乎工作得很好:
split(x,cumsum(x==0))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1021 次 |
| 最近记录: |