R:合并重复观察?

时间:2017-05-04 18:33:41

标签: r consolidation

我有一个大型数据框,大约有500,000个观测值(由“ID”标识)和150多个变量。有些观察只出现一次;其他人出现多次(大约10次左右)。我想“折叠”这些多个观察,以便每个唯一ID只有一行,并且第2列:150列中的所有信息都是连接在一起的。我不需要对这些观察进行任何计算,只需快速修改。

我试过了:

df.new <- group_by(df,"ID")

还有:

library(data.table)
dt = data.table(df)
dt.new <- dt[, lapply(.SD, na.omit), by = "ID"]

并且遗憾的是两者都没有奏效。任何帮助表示赞赏!

3 个答案:

答案 0 :(得分:0)

怎么样?

df %>%
  group_by(ID) %>%
  summarise_each(funs(paste0(., collapse = "/")))

reproducible ...

iris %>%
  group_by(Species) %>%
  summarise_each(funs(paste0(., collapse = "/")))

答案 1 :(得分:0)

我过去遇到过类似的问题,但我并没有处理相同数据的多个副本。在许多情况下只有2个实例,在某些情况下只有3个实例。以下是我的方法。希望它会有所帮助。

idx <- duplicated(df$key) | duplicated(df$key, fromLast=TRUE) # get the index of the duplicate entries. Or will help get the original value too.
dupes <- df[idx,] # get duplicated values
non_dupes <- df[!idx,]  # get all non duplicated values

temp <- dupes %>% group_by(key) %>%  # roll up the duplicated ones.
  fill_(colnames(dupes), .direction = "down") %>%  
  fill_(colnames(dupes), .direction = "up")  %>%  
  slice(1)  

然后很容易合并tempnon_dupes

修改

我强烈建议尽可能将df过滤到最适合的人群并与您的最终目标相关,因为此过程可能需要一段时间。

答案 2 :(得分:0)

使用基本R:

df = data.frame(ID = c("a","a","b","b","b","c","d","d"),
                day = c("1","2","3","4","5","6","7","8"),
                year = c(2016,2017,2017,2016,2017,2016,2017,2016),
                stringsAsFactors = F)

> df
  ID day year
1  a   1 2016
2  a   2 2017
3  b   3 2017
4  b   4 2016
5  b   5 2017
6  c   6 2016
7  d   7 2017
8  d   8 2016

<强>执行:

z = aggregate(df[,2:3], 
              by = list(id = df$ID), 
              function(x){ paste0(x, collapse = "/") }
              )

<强>结果:

> z
  id   day           year
1  a   1/2      2016/2017
2  b 3/4/5 2017/2016/2017
3  c     6           2016
4  d   7/8      2017/2016

修改

如果你想避免&#34;崩溃&#34; NA做:

z = aggregate(df[,2:3], 
              by = list(id = df$ID), 


        function(x){ paste0(x[!is.na(x)],collapse = "/") })

对于数据框,如:

> df
  ID  day year
1  a    1 2016
2  a    2   NA
3  b    3 2017
4  b    4 2016
5  b <NA> 2017
6  c    6 2016
7  d    7 2017
8  d    8 2016

结果是:

> z
  id day           year
1  a 1/2           2016
2  b 3/4 2017/2016/2017
3  c   6           2016
4  d 7/8      2017/2016