r - 通过用户定义的截止将框架拆分为列表
问题描述
想通过 cutoff将df
帧拆分为嵌套列表:df.listing
index_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 数据集提供可重现的示例而道歉。
解决方案
我们需要将逻辑索引的累积和作为拆分组
split(df, cumsum(df$m %in% index_cutoff))
在 OP 的代码中,只有两组,即 TRUE 和 FALSE 来自df$m %in% index_cutoff
. 通过这样做cumsum
,它会通过在每个 TRUE 值上加 1 来改变
推荐阅读
- xml - 自定义用户创建模板 onchange 不起作用
- ios - 以 Debug 与 Release 运行时 CPU 使用率较高(仪器以 Release 运行)。如何调试?
- html - 得到
- javascript - Window.onUnload 不一致地向服务器发送结果
- python - 将 var 合并到 2 个文件中,只匹配一些 var python
- python - 在绘图条形图中更改颜色
- eclipse - Tomcat 重复从 Eclipse 运行的 httpHeaderSecurity
- discord - Discord GitHub Webhook 添加角色 ping
- docker - 码头工人:为什么无法连接到种子
- database - 找出客户与图形数据库中最受欢迎的产品一起购买了什么