I would like to write a function that can combine/rewrite many similarly named variables. In plain English, I would like to change the value of var1
to the value of var1a
when the observation is made in Wave 4. I have to do this 37 times, and I would like to avoid writing out basically identical lines of code 37 times.
df <- df %>% mutate(var1=case_when(wave==4~var1a))
df <- df %>% mutate(var2=case_when(wave==4~var2a))
df <- df %>% mutate(var3=case_when(wave==4~var3a))
I tried doing this... but I kept getting an error code that says that there is an unexpected =
after vvar[i]
.
vvar <- c("var1","var2","var3")
vvara <- c("var1a","var2a","var3a")
for(i in 1:3){
df.test <- df %>% mutate(vvar[i]=case_when(wave==4~vvara[i]))
}
I also tried the following... and the error is that the replacement has no length.
renamefunc <- function(dataset,vars1,vars2){
for (i in 1:length(vars1)){
dataset1 <- ifelse(dataset$wave==4,dataset$vars2[i],dataset$vars1[i])
}
return(dataset1)
}
z <- renamefunc(df,vvar,vvara)