For loop to create new variables

Hi,

Thanks. I am getting super frustrated with loops. What am I getting wrong here?

rm(list = ls())
library(wooldridge)
data(wage2)
head(wage2)
for (v in c("exper", "tenure",  "age" )) {        
  wage2[[v]]2<-wage2[[v]]^2
}

I am getting the error:
Error: unexpected numeric constant in:

Thanks

This is not valid syntax, how do you expect this to be evaluated? In other words what should be the result in your head?

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

wage2 <- data.frame(exper = 1:5,
                    tenure = 6:10,
                    age = 11:15)

for (v in c("exper", "tenure",  "age" )) {  
    wage2[[paste0(v,2)]]<-wage2[[v]]^2
}

wage2
#>   exper tenure age exper2 tenure2 age2
#> 1     1      6  11      1      36  121
#> 2     2      7  12      4      49  144
#> 3     3      8  13      9      64  169
#> 4     4      9  14     16      81  196
#> 5     5     10  15     25     100  225

Created on 2020-04-05 by the reprex package (v0.3.0)

But using loops is not the best way to go for this kind of tasks, there are better tools for the job on the R world

library(dplyr)

wage2 <- data.frame(exper = 1:5,
                    tenure = 6:10,
                    age = 11:15)

wage2 %>% 
    mutate_all(list(`2`=~.^2))
#>   exper tenure age exper_2 tenure_2 age_2
#> 1     1      6  11       1       36   121
#> 2     2      7  12       4       49   144
#> 3     3      8  13       9       64   169
#> 4     4      9  14      16       81   196
#> 5     5     10  15      25      100   225

I was hoping to do the following (squaring my variables):

wage2$exper2<-wage2$exper^2
wage2$tenure2<-wage2$tenure^2
wage2$age2<-wage2$age^2

I thought first I could do

for (v in c("exper", "tenure",  "age" )) {        
  wage2$v2<-wage2$v^2
}

but it did not work either...

Thanks