gpt4 book ai didi

r - 将数据帧拆分为包含一对的较小数据帧列表

转载 作者:行者123 更新时间:2023-12-02 16:05:05 26 4
gpt4 key购买 nike

我想知道如何在下面拆分我的数据,以便我得到一个较小的 dataf.rames 列表,每个 dataf.rames 都包含一对独特的 type

我的 desired_output 如下所示。

请注意,这只是一个玩具数据,因此 type 可以是任何其他变量。另外,请注意,如果特定的 type 只有一行(如 type == 4),我想排除它并发出警告:

类型 4 只有一行,因此被排除在外。

m=
"
obs type
1 1
2 1
3 a
4 a
5 3
6 3
7 4
"
data <- read.table(text = m, h=T)


desired_output <-list(

data.frame(obs=1:4, type=c(1,1,"a","a")),

data.frame(obs=c(1,2,5,6), type=c(1,1,3,3)),

data.frame(obs=3:6, type=c("a","a",3,3))
)

# warning: type 4 has just one row thus is excluded.

最佳答案

这是基本的 R 函数 -

return_list_data <- function(data, type) {
unique_counts <- table(data[[type]])
single_count <- names(unique_counts[unique_counts == 1])
if(length(single_count)) {
warning(sprintf('%s %s has just one row thus is excluded.', type, toString(single_count)))
}
multiple_count <- names(unique_counts[unique_counts > 1])

combn(multiple_count, 2, function(x) {
data[data[[type]] %in% x, ]
}, simplify = FALSE)
}

返回 -

return_list_data(data, 'type')

#[[1]]
# obs type
#1 1 1
#2 2 1
#5 5 3
#6 6 3

#[[2]]
# obs type
#1 1 1
#2 2 1
#3 3 a
#4 4 a

#[[3]]
# obs type
#3 3 a
#4 4 a
#5 5 3
#6 6 3

#Warning message:
#In return_list_data(data, "type") :
# type 4 has just one row thus is excluded.

如果没有单行的 type,即 return_list_data(data[-7, ], 'type'),则不会生成警告。

关于r - 将数据帧拆分为包含一对的较小数据帧列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69640229/

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