Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Apply String Vector to Logical Vector

Tags:

r

I would like to replace any instances of TRUE in a logical vector with the corresponding elements of a same-lengthed string vector.

For example, I would like to combine:

my_logical <- c(TRUE, FALSE, TRUE)
my_string <- c("A", "B", "C")

to produce:

c("A", "", "C")

I know that:

my_string[my_logical]

gives:

"A" "C"

but can't seem to figure out how to return a same-lengthed vector. My first thought was to simply multiply the vectors together, but that raises the error "non-numeric argument to binary operator."

like image 622
b.d Avatar asked Aug 17 '18 13:08

b.d


2 Answers

Another option with replace

replace(my_string, !my_logical, "")
#[1] "A" ""  "C"
like image 128
Ronak Shah Avatar answered Oct 29 '22 12:10

Ronak Shah


What about:

my_logical <- c(TRUE, FALSE, TRUE)
my_string <- c("A", "B", "C")
my_replace <- ifelse(my_logical==TRUE,my_string,'')
my_replace
[1] "A" ""  "C"

Edit, thanks @www:

ifelse(my_logical, my_string, "")
like image 21
s__ Avatar answered Oct 29 '22 13:10

s__