我有以下向量input:
input <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2)
[1] 1 2 1 NA 3 2 NA 1 5 6 NA 2 2
Run Code Online (Sandbox Code Playgroud)
我想按每个 NA 将这个向量分成多个向量。所以期望的输出应该是这样的:
> output
[[1]]
[1] 1 2 1
[[2]]
[1] 3 2
[[3]]
[1] 1 5 6
[[4]]
[1] 2 2
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,每次 aNA出现时,它都会分裂成一个新的向量。所以我想知道是否有人知道如何将一个向量分割NA成多个向量?
tmf*_*mnk 10
使用与 @tpetzoldt 类似的逻辑,但在拆分之前删除 NA:
split(na.omit(input), cumsum(is.na(input))[!is.na(input)])
$`0`
[1] 1 2 1
$`1`
[1] 3 2
$`2`
[1] 1 5 6
$`3`
[1] 2 2
Run Code Online (Sandbox Code Playgroud)
一种方法可能如下:
NAscumsumNAsinput <- c(1,2,1,NA,3,2,NA,1,5,6,NA,2,2)
tmp <- cumsum(is.na(input))
lapply(split(input, tmp), na.omit)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
953 次 |
| 最近记录: |