x1 <- c("agree","disagree","agree","agree","agree","disagree","disagree")
如何替换数据框中的大型原子矢量或特定行/列的agree=1
和disagree=0
?
答案 0 :(得分:4)
你可以做这样的事情
ifelse(x1 == 'agree', 1, 0)
可以根据需要添加更多条件。
答案 1 :(得分:4)
我们可以使用+
将逻辑转换为二进制
+(x1=="agree")
或使用as.integer
(根据评论)
as.integer(x1 == "agree")
此方法比ifelse
快得多。
set.seed(24)
x2 <- sample(c("agree", "disagree"), 1e7, replace=TRUE)
system.time(+(x2=="agree"))
# user system elapsed
# 0.32 0.06 0.40
system.time(ifelse(x2=="agree", 1,0))
# user system elapsed
# 3.20 0.91 4.10