Home > Software design >  R: creating a new vector based on condition of another vector
R: creating a new vector based on condition of another vector

Time:06-29

I have this vector:

x1<-c(1,2,2,2,2,2,3,3,3,4,4,4,4,4,4,4,4,4,4)

I want to create another vector of the same length that has "A" where any element in x1 is <3 and "B" otherwise.

The resulting vector would be:

c("A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","B","B","B")

CodePudding user response:

An alternative will be:

c("B", "A")[1   (x1 < 3)]
# [1] "A" "A" "A" "A" "A" "A" "B" "B" "B" "B" "B" "B" "B" "B" "B" "B" "B" "B" "B"

Benchmark

x1 <- c(1,2,2,2,2,2,3,3,3,4,4,4,4,4,4,4,4,4,4)

bench::mark("zheyuan-li" = ifelse(x1 < 3, "A", "B")
          , "Quinten" = c("B","A")[1   (x1 %in% c(1,2))]
          , "GKi" = c("B", "A")[1   (x1 < 3)]
            )
#  expression      min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc
#  <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>
#1 zheyuan-li   5.86µs   8.13µs    92914.      600B     9.29  9999     1
#2 Quinten      1.38µs   1.87µs   474289.      600B    47.4   9999     1
#3 GKi        640.87ns    851ns  1099866.      400B     0    10000     0

CodePudding user response:

Another option:

c("B","A")[1   (x1 %in% c(1,2))]

Output:

 [1] "A" "A" "A" "A" "A" "A" "B" "B" "B" "B" "B" "B" "B" "B" "B" "B" "B" "B" "B"
  • Related