jeudi 2 juillet 2020

Conditionally removing a vector element

I have two vectors a, b where b can be 1 unit longer than a. In such case I need to remove the last element of vector b to make them equal. I tried following:

a <- c(1:3)
b <- c(1:4)

b <- ifelse(length(a) != length(b), b[-length(b)], b)
b <- ifelse(length(a) != length(b), b[-NROW(b)], b)

In both case, I get

> b
[1] 1

But when I do this out of ifelse() then I can get what I expect:

c <- c(1:4)
c <- c[-length(c)]

> c
[1] 1 2 3

I know how to write this using "if", but I am looking for a better option.

Aucun commentaire:

Enregistrer un commentaire