Home > Blockchain >  How to assign elements to zero if not in a vector in R?
How to assign elements to zero if not in a vector in R?

Time:06-15

Supposed I have a vector:

v <- c(a=1, b=2, c=3, d=4)
v
a b c d 
1 2 3 4 

I would like to create a new vector, new_v, such that: if an element can be found in v, it equals to the value in v, otherwise assign to 0. For example, e, f, and g don't exist in v and they all are assigned as 0, such that:

> new_v
a b c d e f g 
1 2 3 4 0 0 0 

I know it can be created by ifelse for each eletment. Since I have a long vector, I am wondering what the best way to create it.

CodePudding user response:

Use setdiff with the names of the vector and assign those to 0 instead of a conditional expression

v[setdiff(letters[1:7], names(v))] <- 0

-output

> v
a b c d e f g 
1 2 3 4 0 0 0 

CodePudding user response:

Another possible solution, based on intersect:

v <- c(a=1, b=2, c=3, d=4)

new_v <- rep(0, 7)
names(new_v) <- letters[1:7]

new_v[intersect(names(v), names(new_v))] <- v
new_v

#> a b c d e f g 
#> 1 2 3 4 0 0 0
  •  Tags:  
  • r
  • Related