如何在 R 中组合同一数据框中的行(基于特定列下的重复值)? [英] How can I combine rows within the same data frame in R (based on duplicate values under a specific column)?

查看:20
本文介绍了如何在 R 中组合同一数据框中的行(基于特定列下的重复值)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Sample of 2 (made-up) example rows in df:

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

假设我有几百个重复的用户 ID,就像上面的例子一样.但是,绝大多数用户 ID 具有不同的值.

Suppose that I have a couple hundred duplicate userid like in the above example. However, the vast majority of userid have different values.

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

How can I combine rows with duplicate userid in such a way as to stick to the column values in the 1st (of the 2) row unless the first value is NA (in which case the NA will be repopulated with whatever value came from the second row)?

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

In essence, drawing from the above example, my ideal output would contain:

userid   facultyid  courseid schoolid
167       265        301       1678  

推荐答案

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(.))))

这篇关于如何在 R 中组合同一数据框中的行(基于特定列下的重复值)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆