I'm having trouble combining writing in a certain column of a certain dataset in a for loop. Basically I have identically structered datasets w2,w4,w5,w6,w7,w8 and I want to perform the same operation on the same column of each dataset. For example, I want to recode the gender variable from 1 = male, 2 = female to 0 = male,1 = female and then factor it. Here is how I do it for w2.
w2$gender <- case_when(w2$gender == 1 ~ 0, w2$gender == 2 ~ 1)
w2$gender <- factor(w2$gender,
levels = c(0,1),
labels = c("Male","Female"))
I want to build a for loop that does it for all my dataframes, but I'm constantly running into issues as I can't seem to adress the column of the changing dataset.
for(i in w){
z <- paste0("w",i)
eval(call( "<-",eval(as.name(z))[,4], case_when(eval(as.name(z))[,4] == 1 ~ 0, eval(as.name(z))[,4] == 2 ~ 1)))
}
I get the error:
Error in c(2, 2, 2, 1, 2, 1, 1, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 2, 2, 1, : invalid (do_set) left-hand side to assignment
I tried sevral different approaches like using assign function etc. but nothing seems to work. Do you know of an easy way how this could be done?