R使用每列的特定功能将多行折叠为1行 [英] R collapse multiple rows into 1 row using specific function to each column

查看:42
本文介绍了R使用每列的特定功能将多行折叠为1行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下一个数据集:

id <- c(1,1,1,2,2,2)
col_a <- c(123,56,87,987,1003,10)
col_b <- c(17,234,20,88,765,69)
col_c <- c(45,90,543,NA,1,543)
df <- data.frame(id,col_a,col_b,col_c)
library(data.table)
setDT(df)

使用按ID分组我需要为每列应用不同的功能:例如,
:col_a的最小值,col_b的中位数和col_c的最大值,以生成下一个结果:

Using grouping by id I need to apply for each column different function: for example: min for col_a, median for col_b and max for col_c, to generate next result:

id  col_a col_b col_c
1   56    20   543
2   10    88   543

需要完成像这样的解决方案:

Need to complete solution like this:

df[, lapply(.SD, ???), by=id]  


推荐答案

我们可以使用 Map 将每个函数应用于按' id'

We can use Map to apply each of the functions to the corresponding columns grouped by 'id'

df[, Map(function(x,y) get(x)(y, na.rm = TRUE), 
       setNames(c('min', 'median', 'max'),names(.SD)), .SD), by = id]
#   id col_a col_b col_c
#1:  1    56    20   543
#2:  2    10    88   543

这篇关于R使用每列的特定功能将多行折叠为1行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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