[英]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. 我想使用汽车资料库中的recode
来分配一组新的变量y1
和y2
,但我不想手工完成。
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
. 我试图遍历var_list
,然后使用assign
和paste
对变量d1$y1
和d1$y2
。 The use of recode
is conventional to that package and not the the source of my error (i imagine!) 使用recode
是该程序包的常规功能,而不是我的错误来源(我想!)
what am i doing wrong here? 我在这里做错了什么?
Here is a more "R-ish" approach that still uses recode()
: 这是一种更“ R-ish”的方法,仍然使用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 没有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 与plyr
d2 <- colwise(recode)(d1,recodes="1:2 ='a'; 3:4 = 'b'")
names(d2) <- vn2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.