when recoding a set of variables which all have the same format, i’d like to do so in a loop to save time, but the result seems to escape me.
consider the following exampe
d1 <- data.frame(x1 = 1:4,
x2 = 1:4)
i want to use recode from the car library to assign a new set of variables, y1 and y2, but i don’t want to do it by hand.
my infantile approach is
library(car)
var_list <- c("x1", "x2")
for(i in seq_along(var_list)) {
assign(paste("d1$y", match(i, var_list)], sep = ""),
recode(d1$i, "1:2 = 'a';3:4 = 'b'"))}
i’m trying to loop through var_list, and then use assign and paste to number the variables d1$y1 and d1$y2. The use of recode is conventional to that package and not the the source of my error (i imagine!)
what am i doing wrong here?
Here is a more “R-ish” approach that still uses
recode():