本文介绍了在R中查找并替换类别变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
x1 <- c("agree","disagree","agree","agree","agree","disagree","disagree")
如何用大原子矢量或数据帧中特定的行/列替换agree=1
和disagree=0
?
How to replace agree=1
and disagree=0
for large atomic vectors or specific row/columns in a data frame?
推荐答案
我们可以使用+
将逻辑转换为二进制
We can use +
to convert the logical to binary
+(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
这篇关于在R中查找并替换类别变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!