首页 > 解决方案 > 通过删除重复列来压缩数据框,同时保留额外的相应信息

问题描述

很抱歉,我很难清楚地描述我的问题。我在这里举一个例子来表达我想做的事情。

我有一个数据框:

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

非常感谢你的帮助。

标签: rdataframe

解决方案


使用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

推荐阅读