首页 > 解决方案 > 通过用户定义的截止将框架拆分为列表

问题描述

想通过 cutoff将df帧拆分为嵌套列表:df.listingindex_cutoff

数据:

df <- data.frame(m=c("A","T","W","Z","B","A","A","W","T","K","G","B","T","B"))
index_cutoff <- c("A","B")

尝试代码:

df.listing <- split(df, df$m %in% keyword_cutoff) #failed, not working

电流输出:

$`FALSE`
   m
2  T
3  W
4  Z
8  W
9  T
10 K
11 G
13 T

$`TRUE`
   m
1 A
5 B
6 A
7 A
12 B
14 B

所需的输出阶段 1:

df.listing[[1]]
A
T
W
Z

df.listing[[2]]
B

df.listing[[3]]
A

df.listing[[4]]
A
W
T
K
G

df.listing[[5]]
B
T

df.listing[[6]]
B

期望的输出最终:

df.listing[[1]]
A
T
W
Z

df.listing[[2]]
B

df.listing[[3]]
A #since at stage 1 they are the same cutoff, hence self merge into next list
A
W
T
K
G

df.listing[[4]]
B #since at stage 1 they begin the same with "B" cutoff
T
B

感谢您并为无法通过 R 数据集提供可重现的示例而道歉。

标签: r

解决方案


我们需要将逻辑索引的累积和作为拆分组

split(df, cumsum(df$m %in% index_cutoff))

在 OP 的代码中,只有两组,即 TRUE 和 FALSE 来自df$m %in% index_cutoff. 通过这样做cumsum,它会通过在每个 TRUE 值上加 1 来改变


推荐阅读