在 dplyr 中用逗号连接二进制列名
Concatenate binary column names with commas in dplyr
我想创建一个新列,使用相应的类别名称来描述给定样本中存在哪些二进制属性。
这是我的数据示例
sample_id type_1 type_2 type_3
1 0 0 1
2 1 1 0
3 1 1 1
理想情况下,我想创建一个 type
列,按名称汇总所有变量,用逗号分隔,如下所示
type
type_3
type_1, type_2
type_1, type_2, type_3
我已经尝试使用 mutate
和 if_else
来做到这一点,方法是创建另外三列字符串名称或零,但是当涉及到连接值时,我按顺序得到多个逗号其中有零值。
library(dplyr)
df <- read.table(text = "sample_id type_1 type_2 type_3
1 0 0 1
2 1 1 0
3 1 1 1", header = TRUE)
df %>%
rowwise() %>%
mutate(
type = toString(paste0("type ", which(cur_data()[-1L] == 1)))
)
# sample_id type_1 type_2 type_3 type
# <int> <int> <int> <int> <chr>
# 1 1 0 0 1 type 3
# 2 2 1 1 0 type 1, type 2
# 3 3 1 1 1 type 1, type 2, type 3
这是一个基本的 R 选项 -
#get columns names that have type in it
cols <- grep('type', names(df), value = TRUE)
#get row/column number where 1 is present
mat <- which(df[cols] == 1, arr.ind = TRUE)
#For each row combine the column names
df$type <- tapply(mat[, 2], mat[, 1], function(x) toString(cols[x]))
df
# sample_id type_1 type_2 type_3 type
#1 1 0 0 1 type_3
#2 2 1 1 0 type_1, type_2
#3 3 1 1 1 type_1, type_2, type_3
我想创建一个新列,使用相应的类别名称来描述给定样本中存在哪些二进制属性。
这是我的数据示例
sample_id type_1 type_2 type_3
1 0 0 1
2 1 1 0
3 1 1 1
理想情况下,我想创建一个 type
列,按名称汇总所有变量,用逗号分隔,如下所示
type
type_3
type_1, type_2
type_1, type_2, type_3
我已经尝试使用 mutate
和 if_else
来做到这一点,方法是创建另外三列字符串名称或零,但是当涉及到连接值时,我按顺序得到多个逗号其中有零值。
library(dplyr)
df <- read.table(text = "sample_id type_1 type_2 type_3
1 0 0 1
2 1 1 0
3 1 1 1", header = TRUE)
df %>%
rowwise() %>%
mutate(
type = toString(paste0("type ", which(cur_data()[-1L] == 1)))
)
# sample_id type_1 type_2 type_3 type
# <int> <int> <int> <int> <chr>
# 1 1 0 0 1 type 3
# 2 2 1 1 0 type 1, type 2
# 3 3 1 1 1 type 1, type 2, type 3
这是一个基本的 R 选项 -
#get columns names that have type in it
cols <- grep('type', names(df), value = TRUE)
#get row/column number where 1 is present
mat <- which(df[cols] == 1, arr.ind = TRUE)
#For each row combine the column names
df$type <- tapply(mat[, 2], mat[, 1], function(x) toString(cols[x]))
df
# sample_id type_1 type_2 type_3 type
#1 1 0 0 1 type_3
#2 2 1 1 0 type_1, type_2
#3 3 1 1 1 type_1, type_2, type_3