简体   繁体   中英

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.

Best I've been able to come up with is using 2 gsubs.

Assuming I have the vector 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

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