简体   繁体   English

R将逻辑向量替换为“ on”或“ off”

[英]R replace logical vector with “on” or “off”

I'm trying to create a one liner that will replace a logical vector with "on" or "off" based on true or false. 我正在尝试创建一个衬板,该衬板将基于true或false将逻辑向量替换为“ on”或“ off”。

Best I've been able to come up with is using 2 gsubs. 我能想到的最好的方法是使用2 gsubs。

Assuming I have the vector tmp 假设我有矢量tmp

tmp <- sample(100,100)

I can use 我可以用

blah <- tmp > 50
blah <- gsub(FALSE, "no", blah)
blah <- gsub(TRUE, "yes", blah)

to achieve what I want, but I'm betting there's a more elegant solution. 实现我想要的,但是我敢打赌,这里有一个更优雅的解决方案。

使用ifelse

blah <- ifelse(tmp > 50, "yes", "no")

Try 尝试

r1 <- c('no', 'yes')[(tmp>50)+1]
identical(r1, blah)
#[1] TRUE

Or 要么

 r2 <- as.character(factor(tmp>50, labels=c('no', 'yes')))
 identical(r1, r2)
#[1] TRUE

Or 要么

 library(qdap)
 r3 <-  mgsub(c(FALSE, TRUE), c('no', 'yes'), tmp > 50)
 identical(r1,r3)
 #[1] TRUE

Or 要么

 library(car)
 r4 <- recode(tmp>50, "FALSE='no'; TRUE='yes'")
 identical(r1,r4)
 #[1] TRUE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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