在R中使用data.table重命名聚合的列 [英] Rename aggregated columns using data.table in R

查看:240
本文介绍了在R中使用data.table重命名聚合的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表dtTrain,其中有很多列。我正在尝试对每个[Min,Max,sd,mean]执行4个聚合列。
为此,我正在运行该行

I have a table dtTrain which has many columns. I am trying to perform 4 aggregation columns on each, [Min, Max, sd, mean]. To do this I am running the line

subTrain <- dtTrain[,c(min = lapply(.SD, min), 
                       max = lapply(.SD, max), 
                       sd = lapply(.SD, sd), 
                       mean = lapply(.SD, mean)), by=TrialID]

我遇到的问题是聚合工作正常,但列标题重复(即column1在subTrain表中生成了四次)。
我希望 [column1.min,...,column1.max ...,column1.sd,... column1.mean,...] 或实际上是任何列标签。

The problem I am having is the aggregation is working but the column headers are repeated (ie column1 is produced four times in the subTrain table). I would prefer [column1.min,...,column1.max...,column1.sd, ...column1.mean,...] or in fact any column label.

推荐答案

我们可以使用 setnames 使用 rep 更改列名称

We can use setnames with rep to change the column names

res <- dtTrain[, c(lapply(.SD, min), 
        lapply(.SD, max),
        lapply(.SD, sd), 
       lapply(.SD, mean)), by=TrialID]
nm1 <- setdiff(names(dtTrain), 'TrialID')
setnames(res, 2:ncol(res), paste(nm1, rep(c('min', 'max', 'sd', 'mean'), 
                         each = length(nm1)), sep="."))  

这篇关于在R中使用data.table重命名聚合的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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