将多列收集到逗号分隔的列表中
Collecting multiple columns into comma,separated lists
我想根据这个模式在 R 中转换数据框:
请注意,之前的热编码属性 Att_1 是作为逗号分隔列表收集在 IDy 的单个单元格中的。
我如何在 R 中执行此操作(例如使用 tidyr 函数)?
test <- data.frame(ID = c("IDx", "IDy"), Att_1_1 = c(0,0), Att_1_2 = c(1,1), Att_1_3 = c(0, 1), Att_2 = c(1,1), Att_3 = c(1,0))
由于 OP 请求 tidyr
函数,我们 gather
将数据集转换为 'long' 格式,filter
'val' 为 1 的行,分组依据'IDs'、paste
'key' 列创建 summarise
d 列 'Att_1' 和 left_join
'IDs' 使用原始数据集
library(tidyverse)
test %>%
gather(key, val, Att_1_1:Att_1_3) %>%
filter(val==1) %>%
group_by(ID) %>%
summarise(Att_1 = toString(key)) %>%
left_join(df1[-(2:4)], ., by = "ID") %>%
select(ID, Att_1, Att_2, Att_3)
# ID Att_1 Att_2 Att_3
#1 IDx Att_1_2 1 1
#2 IDy Att_1_2, Att_1_3 1 0
在基础 R 中,您可以执行以下操作。
# set up new dataframe
res <- test[-(2:4)]
# add new varible
res$Att_1 <- apply(test[, 2:4], 1, function(x) c(names(test)[2:4][as.logical(x)]))
此处,apply
使用逻辑子集循环遍历名称子集 data.frame 和 returns 向量的行,其中行单元格的值等于 1。
这个returns
res
ID Att_2 Att_3 Att_1
1 IDx 1 1 Att_1_2
2 IDy 1 0 Att_1_2, Att_1_3
注意
res[["Att_1"]] <- ...
也可以。
我想根据这个模式在 R 中转换数据框:
请注意,之前的热编码属性 Att_1 是作为逗号分隔列表收集在 IDy 的单个单元格中的。
我如何在 R 中执行此操作(例如使用 tidyr 函数)?
test <- data.frame(ID = c("IDx", "IDy"), Att_1_1 = c(0,0), Att_1_2 = c(1,1), Att_1_3 = c(0, 1), Att_2 = c(1,1), Att_3 = c(1,0))
由于 OP 请求 tidyr
函数,我们 gather
将数据集转换为 'long' 格式,filter
'val' 为 1 的行,分组依据'IDs'、paste
'key' 列创建 summarise
d 列 'Att_1' 和 left_join
'IDs' 使用原始数据集
library(tidyverse)
test %>%
gather(key, val, Att_1_1:Att_1_3) %>%
filter(val==1) %>%
group_by(ID) %>%
summarise(Att_1 = toString(key)) %>%
left_join(df1[-(2:4)], ., by = "ID") %>%
select(ID, Att_1, Att_2, Att_3)
# ID Att_1 Att_2 Att_3
#1 IDx Att_1_2 1 1
#2 IDy Att_1_2, Att_1_3 1 0
在基础 R 中,您可以执行以下操作。
# set up new dataframe
res <- test[-(2:4)]
# add new varible
res$Att_1 <- apply(test[, 2:4], 1, function(x) c(names(test)[2:4][as.logical(x)]))
此处,apply
使用逻辑子集循环遍历名称子集 data.frame 和 returns 向量的行,其中行单元格的值等于 1。
这个returns
res
ID Att_2 Att_3 Att_1
1 IDx 1 1 Att_1_2
2 IDy 1 0 Att_1_2, Att_1_3
注意
res[["Att_1"]] <- ...
也可以。