如何组合R中相同数据框内的行(基于特定列下的重复值)?

时间:2015-03-13 19:42:01

标签: r duplicates append combiners

df中的2个(虚构的)示例行示例:

userid   facultyid  courseid schoolid
167       265        NA       1678  
167       71111      301      NA

假设我有几百个重复的用户ID,如上例所示。但是,绝大多数userid都有不同的值。

如何将行与重复的用户ID组合起来,以便坚持第1行(第2行)中的列值,除非第一个值是NA(在这种情况下,NA将重新填充任何值从第二行开始)?

从本质上讲,从上面的例子中得出,我的理想输出将包含:

userid   facultyid  courseid schoolid
167       265        301       1678  

4 个答案:

答案 0 :(得分:4)

aggregate(x = df1, by = list(df1$userid), FUN = function(x) na.omit(x)[1])[,-1]

或使用dplyr库:

library(dplyr)

df1 %>%
  group_by(userid) %>%
  summarise_each(funs(first(na.omit(.))))

答案 1 :(得分:1)

# initialize a vector that will contain row numbers which should be erased
rows.to.erase <- c()

# loop over the rows, starting from top
for(i in 1:(nrow(dat)-1)) {
  if(dat$userid[i] == dat$userid[i+1]) {
    # loop over columns to recuperate data when a NA is present
    for(j in 2:4) {
      if(is.na(dat[i,j]))
        dat[i,j] <- dat[i+1,j]
    }
    rows.to.erase <- append(rows.to.erase, i+1)
  }
}

dat.clean <- dat[-rows.to.erase,]
dat.clean
#   userid facultyid courseid schoolid
# 1    167       265      301     1678

答案 2 :(得分:1)

这是使用ddply的另一种方法:

# requires the plyr package
library(plyr)

# Your example dataframe with added lines
schoolex <- data.frame(userid = c(167, 167, 200, 203, 203), facultyid = c(265, 71111, 200, 300, NA), 
                        courseid = c(NA, 301, 302, 303, 303), schoolid = c(1678, NA, 1678, NA, 1678))

schoolex_duprm <- ddply(schoolex, .(userid), summarize, facultyid2 = facultyid[!is.na(facultyid)][1], 
                               courseid2 = courseid[!is.na(courseid)][1], 
                               schoolid2 = schoolid[!is.na(schoolid)][1])

答案 3 :(得分:1)

这是来自plyr的简单单行。我写的比你提出的要多得多:

 a <- data.frame(x=c(1,2,3,1,2,3,1,2,3),y=c(2,3,1,1,2,3,2,3,1),
       z=c(NA,1,NA,2,NA,3,4,NA,5),zz=c(1,NA,2,NA,3,NA,4,NA,5))

 ddply(a,~x+y,summarize,z=first(z[!is.na(z)]),zz=first(zz[!is.na(zz)]))

具体回答原始问题,如果您的数据框命名为a,:

 ddply(a,~userid,summarize,facultyid=first(facultyid[!is.na(facultyid)]),
         courseid=first(courseid[!is.na(courseid)],
         schoolid=first(schoolid[!is.na(schoolid)])