r - 将 data.frame 拆分为包含一对的较小 data.frames 列表
问题描述
我想知道如何拆分我的data
下面,以便我得到一个较小的 dataf.rames 列表,其中每个包含一个唯一的一对type
?
我desired_output
的如下图所示。
请注意,这只是一个玩具数据,因此type
可以是任何其他变量。另外,请注意,如果一个特定type
的只有一行(如type == 4
),我想用一条警告排除它:
type 4 has just one row thus is excluded.
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
with single row ie ,则不会生成警告return_list_data(data[-7, ], 'type')
。
推荐阅读
- angular - API 轮询和超时
- java - 在控制器中接受请求时发生 json 解析错误
- jquery - 如何从进行 ajax 调用中排除页面
- php - 使用 JMS Serializer 在 symfony 4 中反序列化 xml
- c# - 更改 Windows 状态后,ScrollViewer 上的最后一项被截断
- web-services - 如何将值从 html 页面传递到简单的 java 类
- java - MongoDB,2个查询的共同部分
- firebase - 为什么 for 循环在离子 ionViewWillEnter 方法中不起作用
- cmis - 获取具有特定 Aspect 属性值的文件夹或站点中的所有文档?
- bash - Bash basename 只返回文件夹列表中的姓氏