简体   繁体   English

寻求快速或自动化的方法来在R中命名*许多*新的data.table列

[英]Seeking fast or automated method for naming *many* new data.table columns in R

I have a large dataset, 3000x400. 我有一个大型数据集3000x400。 I need to created new columns that are means of the existing columns subsetted by a variable constituency . 我需要创建新列,这些新列是通过可变constituency派生的现有列的​​方法。 I have a list of new columns names that I want to use to name the new columns, below called newNames . 我有一个新列名称的列表,我想使用它们来命名新列,以下称为newNames But I can only figure out how to name columns when I directly type the desired new name. 但是,当我直接输入所需的新名称时,我只能弄清楚如何命名列。

What I currently do: 我目前正在做什么:

set.seed(1)
dataTest = data.table(turnout_avg = rnorm(20), urban_avg = rnorm(20,5,2), Constituency = c("A","B","C","D"), key = "Constituency")

oldColumnNames = c( "turnout_avg" , "urban_avg")

newNames = c( "turnout" ,   "urban")

# Here's my problem, naming these new columns
comm_means_by_district = cbind( 
dataTest[,list(Const_turnout = mean(na.omit(get(oldColumnNames[[1]])))), by= Constituency],
dataTest[,list(Const_urban = mean(na.omit(get(oldColumnNames[[2]])))),by= Constituency])

In reality, I want to create much more than two new columns. 实际上,我想创建两个以上的新列。 So I cannot feasibly type Const_turnout , Const_urban , etc. for all new columns. 因此,我无法为所有新列键入Const_turnoutConst_urban等。

I've have tried two ideas, but neither works, 1. 我已经尝试了两个想法,但都没有成功,1。

dataTest[,list(paste("district", newNames[1], sep="_") = mean(na.omit(get(refColNames[[1]])))), by= Constituency]

Or 2. 或2。

dataTest[,list(paste(oldColumnNames[1], "constMean", sep="_") = mean(na.omit(get(refColNames[[1]])))), by= Constituency]

first get the mean of all the columns in one go 首先一次性获得所有列的均值

DT <- dataTest[,lapply(.SD,function(x) mean(na.omit(x))), by= Constituency]

then change the colnames afterwards 然后更改名字

setnames(DT,colnames(DT),vector_of_newnames)

Why is it important to change the names in the same line where you apply the function? 为什么在应用该功能的同一行中更改名称很重要? I would just first calculate the constituency-wise means and set the column names after. 我只想先计算选区商的平均值,然后再设置列名。 Here's how this would look like: 这是这样的:

dt <- dataTest[, lapply(oldColumnNames, function(x) mean(na.omit(get(x)))), 
               by=Constituency]
setnames(dt, c("Constituency", paste("Const", newNames, sep="_")))
dt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM