简体   繁体   中英

using seq_along, paste to recode in a loop

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

d2 <- lapply(d1, FUN=function(X) recode(X, "1:2 ='a'; 3:4 = 'b'"))
names(d2) <- gsub("x", "y", names(d2))
d1 <- data.frame(d1,d2)
d1
#  x1 x2 y1 y2
# 1  1  1  a  a
# 2  2  2  a  a
# 3  3  3  b  b
# 4  4  4  b  b

Without plyr

vn1 <- names(d1)
vn2 <- gsub("x","y")

d2 <- data.frame(lapply(structure(.Data=vn1, .Names=vn2), 
                        FUN=function(X) recode(d1[[X]], "1:2 ='a'; 3:4 = 'b'")))

With plyr

d2 <- colwise(recode)(d1,recodes="1:2 ='a'; 3:4 = 'b'")
names(d2) <- vn2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM