0

What I need to do is to do is to create new variables ("new_var" in my code) using the ave function

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

by changing each time the grouping variable ("new_year" in my code) according to the above mentioned documentation

I have tried replacing the variable new_year with colnames(dat)[colnames(dat)==new_year] and with dat[new_year] but the code didn't work

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
})

}

I expect to create new columns in my data set with the names :

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

according to the outputs of ave function in which the new year changes as following new_year_1990,new_year_1991,new_year_1992,.....

John
  • 13
  • 2
  • 3
    It's not clear to me what you're trying to do. Can you please make your post reproducible by including minimal & representative sample data and your matching expected output? For more information, see how to provide a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Maurits Evers Jul 14 '19 at 23:36

1 Answers1

0

Here, we are passing strings into ave and assign with a string. Instead of within, we can use with and then assign the columns to the dataset to the lhs using [[

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))


 }

A reproducible example

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
akrun
  • 874,273
  • 37
  • 540
  • 662