我想知道如何拆分我的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.
uj5u.com熱心網友回復:
這是基本的 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單行 ie沒有,則不會生成警告return_list_data(data[-7, ], 'type')。
uj5u.com熱心網友回復:
您可以嘗試使用dplyr,
df1 <- read.table(text = m, h=T)
fun <- function(df1){
df2 <- df1 %>%
group_by(type) %>%
filter(n() > 1)
df3 <- combn(unique(df2$type), 2) %>% as.data.frame
df4 <- lapply(df3, function(x){
df2 %>%
filter(type %in% x)
})
war <- df1 %>%
group_by(type) %>%
filter(n()<= 1) %>%
pull(type)%>%
unique
if (length(war)>0){
warning(paste("type", war, "has just one row thus is excluded"))}
return(df4)
}
fun(df1)
結果:
$V1
# A tibble: 4 x 2
# Groups: type [2]
obs type
<int> <chr>
1 1 1
2 2 1
3 3 a
4 4 a
$V2
# A tibble: 4 x 2
# Groups: type [2]
obs type
<int> <chr>
1 1 1
2 2 1
3 5 3
4 6 3
$V3
# A tibble: 4 x 2
# Groups: type [2]
obs type
<int> <chr>
1 3 a
2 4 a
3 5 3
4 6 3
Warnings: In fun(df1) : type 4 has just one row thus is excluded
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/326981.html
上一篇:如何找到我的混淆矩陣的準確性?
下一篇:自動停止圖例被圖裁剪(R)
