gpt4 book ai didi

r - 通过用户定义的截止值将帧拆分为列表

转载 作者:行者123 更新时间:2023-12-04 09:36:28 26 4
gpt4 key购买 nike

想拆分一个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 的代码中,只有两组,即来自 df$m %in% index_cutoff 的 TRUE 和 FALSE .通过做 cumsum ,它通过在每个 TRUE 值处加 1 来改变

关于r - 通过用户定义的截止值将帧拆分为列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50449605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com