我的输入数据框架包含100多个列和行。如果列的头是相同的,我想将它们组合起来。
以下是我的输入数据框架
Case.ID HRAS TP53 MAP3K1 MAP3K1 TP53
TCGA_1 MSE; MSE;
TCGA_2 MUT;
TCGA_3
TCGA_4 MUT; AMP;
TCGA_5 MSE;
TCGA_6
TCGA_7 MUT;
TCGA_8 MUT; AMP;
TCGA_9 MUT;
TCGA_10
TCGA_11 FRM; st_gai;
TCGA_12 HDEL;预期产出
Case.ID HRAS TP53 MAP3K1
TCGA_1 MSE;
TCGA_2 MUT;
TCGA_3
TCGA_4 MUT;AMP;
TCGA_5 MSE;
TCGA_6
TCGA_7 MUT;
TCGA_8 MUT; AMP;
TCGA_9 MUT;
TCGA_10
TCGA_11 FRM;st_gai;
TCGA_12 HDEL; 在预期的输出中,您可以看到我组合了相同的标题列,如果它们在行中有相同的条目,那么它将只打印一次,如果一行中有不同的条目,那么所有的条目都将合并在一起。在这里,他们只是组合了选定的列Combine two or more columns in a dataframe into a new column with a new name
发布于 2022-08-07 14:47:40
您可以尝试将其转换为长格式,然后在使用str_remove调整名称之后,我们可以使用粘贴值的values_fn将其放大。
librray(tidyr)
cbind(Case.ID = rownames(df), stack(df[-1])) |>
transform(ind = as.character(ind) |> stringr::str_remove_all("\\.\\d")) |>
pivot_wider(Case.ID, names_from = ind, values_from = values,
values_fn = \(x) paste(unique(x), collapse = ""))这假设Case.Id是行名,而不是列,因为在给出数据时它就是这样出现的。如果Case.Id最初是一个列,那么您可以这样做
cbind(df[-1], stack(df[-1])而不是cbind(Case.ID = rownames(df), stack(df[-1]))
Case.ID HRAS TP53 MAP3K1
<chr> <chr> <chr> <chr>
1 TCGA_1 "" "MSE;" ""
2 TCGA_2 "" "" ""
3 TCGA_3 "" "" ""
4 TCGA_4 "" "MUT;AMP;" ""
5 TCGA_5 "" "" "MSE;"
6 TCGA_6 "" "" ""
7 TCGA_7 "MUT;" "" ""
8 TCGA_8 "MUT;" "AMP;" ""
9 TCGA_9 "MUT;" "" ""
10 TCGA_10 "" "" ""
11 TCGA_11 "" "" "FRM;st_gai;"
12 TCGA_12 "" "HDEL;" "" https://stackoverflow.com/questions/73268203
复制相似问题