Home > Net >  Generating a vector of values from logical and numeric vectors of different lengths
Generating a vector of values from logical and numeric vectors of different lengths

Time:04-12

My question is certainly very basic, though I'm struggling to find a proper solution in this forum. I have a logical vector (v1) and numeric (v2) vector with different lengths. The length of v2 is equal to the sum of TRUE values in v1.

My goal is to create a third vector (v3), with the same number of elements as v1, assigning NA whenever v1 == FALSE and using the values in v2 to "populate" v3 when v1 == TRUE. Something like this:

v1 <- c( FALSE, TRUE, TRUE, FALSE, FALSE , TRUE )

v2 <- c(3, 0, 2)

Desired output (v3): NA, 3, 0, NA, NA, 2

Thanks!

CodePudding user response:

A one-liner with replace:

replace(rep(NA, length(v1)), v1, v2)
[1] NA  3  4 NA NA  2

Or, with [:

v1[v1] <- v2
# [1] 0 3 4 0 0 2

v1[v1 == 0] <- NA
# [1] NA  3  4 NA NA  2

CodePudding user response:

Another possible solution, based on dplyr:

library(dplyr)

v1 %>% na_if(F) %>% replace(which(.), v2)

#> [1] NA  3  0 NA NA  2

CodePudding user response:

For educational purposes. A throwaway function, using NA propagation.

(\(){.=v1[NA];.[v1]=v2;.})()
[1] NA  3  0 NA NA  2

CodePudding user response:

Just do:

v1 <- c( FALSE,  TRUE,  TRUE,  FALSE,  FALSE , TRUE )
v2 <- c(3, 4, 2)
v3<-v1

v3[v3==T] <- v2
v3[v3==0] <- NA
  • Related