【问题标题】:How can I add a dynamic variable name in the R function ave using a for loop?如何使用 for 循环在 R 函数 ave 中添加动态变量名称?
【发布时间】:2019-07-14 23:29:46
【问题描述】:

我需要做的是使用 ave 函数创建新变量(我的代码中的“new_var”)

https://www.rdocumentation.org/packages/stats/versions/3.6.0/topics/ave

根据上述文档每次更改分组变量(我的代码中的“new_year”)

我尝试用 colnames(dat)[colnames(dat)==new_year] 和 dat[new_year] 替换变量 new_year,但代码不起作用

for (year in 1990:2015){

new_var <- paste("active_year_calc", year , sep="_")
new_year <- paste("active_year", year , sep="_")

dat <- within(dat, {
  new_var<-ave(sum_variable, company_name,new_year, FUN = length
})

}

我希望在我的数据集中使用名称创建新列:

active_year_calc_1990, active_year_calc_1991,active_year_calc_1992,......active_year_calc_2015

根据 ave 函数的输出,新年变化如下 new_year_1990,new_year_1991,new_year_1992,.....

【问题讨论】:

  • 我不清楚您要做什么。您能否通过包含最少且具有代表性的样本数据和匹配的预期输出来使您的帖子可重现?如需更多信息,请参阅如何提供minimal reproducible example

标签: r


【解决方案1】:

在这里,我们将字符串传递给ave 并分配一个字符串。我们可以使用with 代替within,然后使用[[ 将数据集的列分配给lhs

for (year in 1990:2015){

  new_var <- paste("active_year_calc", year , sep="_")
  new_year <- paste("active_year", year , sep="_")

  dat[[new_var]] <- with(dat, ave(sum_variable, company_name, 
            get(new_year), FUN = length))


 }

一个可重现的例子

new_var1 <- "gear_Length"
new_gear <- "gear"
mtcars[[new_var1]] <- with(mtcars, ave(drat,  get(new_gear), FUN = length))
head(mtcars, 2)
#              mpg cyl disp  hp drat    wt  qsec vs am gear carb gear_Length
#Mazda RX4      21   6  160 110  3.9 2.620 16.46  0  1    4    4          12
#Mazda RX4 Wag  21   6  160 110  3.9 2.875 17.02  0  1    4    4          12

【讨论】:

    猜你喜欢
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多