如何使用R中的自定义函数聚合data.frame中的多个列?

苹果电脑

我有一个data.frame dt,其中包含一些重复的键和丢失的数据,即

Name     Height     Weight   Age
Alice    180        NA       35
Bob      NA         80       27
Alice    NA         70       NA
Charles  170        75       NA

在这种情况下,键就是名称,我想将类似

f <- function(x){
  x <- x[!is.na(x)]
  x <- x[1]
  return(x)
  }

同时通过键(即“名称”列)进行汇总,从而获得

Name     Height     Weight   Age
Alice    180        70       35
Bob      NA         80       27
Charles  170        75       NA

我试过了

dt_agg <- aggregate(. ~ Name,
                    data = dt,
                    FUN = f)

我遇到了一些错误,然后尝试了以下操作

dt_agg_1 <- aggregate(Height ~ Name,
                      data = dt,
                      FUN = f)

dt_agg_2 <- aggregate(Weight ~ Name,
                      data = dt,
                      FUN = f)

这次它起作用了。

由于我有50列,因此第二种方法对我来说很麻烦。有没有办法解决第一种方法?

感谢帮助!

avid_useR

您可以使用dplyr

library(dplyr)
df %>%
  group_by(Name) %>%
  summarize_all(funs(sort(.)[1]))

结果:

# A tibble: 3 x 4
     Name Height Weight   Age
   <fctr>  <int>  <int> <int>
1   Alice    180     70    35
2     Bob     NA     80    27
3 Charles    170     75    NA

数据:

df = read.table(text = "Name     Height     Weight   Age
Alice    180        NA       35
Bob      NA         80       27
Alice    NA         70       NA
Charles  170        75       NA", header = TRUE)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章