r - 通过删除重复列来压缩数据框,同时保留额外的相应信息
问题描述
很抱歉,我很难清楚地描述我的问题。我在这里举一个例子来表达我想做的事情。
我有一个数据框:
a = data.frame(gene = c("A", "A", "A", "B", "B", "C"),
id = c(100, 100, 30, 250, 250, 600),
where = c("human", "flow", "apple", "human", "rock", "ghost"))
我想删除重复的行,同时保留一些信息,并获得如下输出:
gene id where
A 100, 30 human, flow, apple
B 250 human, rock
C 600 ghost
非常感谢你的帮助。
解决方案
使用dplyr
.
library(dplyr)
a2 <- a %>%
group_by(gene) %>%
summarize_all(list(~toString(unique(.))))
a2
# # A tibble: 3 x 3
# gene id where
# <fct> <chr> <chr>
# 1 A 100, 30 human, flow, apple
# 2 B 250 human, rock
# 3 C 600 ghost
或使用data.table
.
library(data.table)
setDT(a)[, lapply(.SD, function(x) toString(unique(x))), by = gene][]
# gene id where
# 1: A 100, 30 human, flow, apple
# 2: B 250 human, rock
# 3: C 600 ghost
或基数 R。
aggregate(x = a[, !names(a) %in% "gene"], by = a[, "gene", drop = FALSE],
function(x) toString(unique(x)))
# gene id where
# 1 A 100, 30 human, flow, apple
# 2 B 250 human, rock
# 3 C 600 ghost
推荐阅读
- c# - 如何在 .netframework 项目中使用通用 Windows 运行时 api
- flutter - Navigator:将所有内容推送到 home 路线之后
- java - 我应该使用哪种编码方法?
- amazon-web-services - Keep getting Terraform Error for S3 Replication
- google-chrome-devtools - 是否可以在 Mac 的源 javascript 文件中的 chrome 开发人员工具中找到匹配的括号
- automapper - AutoMapper - 如何解决丢失的映射?
- javascript - 反应 | 如何动态渲染有限数量的组件
- r - 将(且仅用于)已删除的反向重复项与未删除的反向原件的列值与 R 相加
- r - 尝试使用 str_match() 来识别文本中的一些数字
- json - Ajax JSON.parse 不会填充所有数据