Home > Blockchain >  Is there an R function to fill up values conditional to column?
Is there an R function to fill up values conditional to column?

Time:11-01

I have an example object of

a <- 1 2 3 4 5 with dimension names 2001 2002 2003 2004 2005

I have another object of

b <- 11 22 33 44 55 with dimension names 1999 2001 2003 2006 2007

I have a year vector

year <- c (1999:2007)

I want to fill up the values of a that are currently missing for the years between 1999 and 2007 with NA.

Similarly, I want to fill up the values of b that are currently missing for the years between 1999 and 2007 with NA.

CodePudding user response:

Assuming that 'a' and 'b' are named vectors, create a named vector of NAs with 'year' vector, and then use the names of 'a' to assign the values of 'a' into that new vector

v1 <- setNames(rep(NA, length(year)), year)
v1[names(a)] <- a

Similarly, do this on 'b' as well

v2 <- setNames(rep(NA, length(year)), year)
v2[names(b)] <- b

-output

> v2
1999 2000 2001 2002 2003 2004 2005 2006 2007 
  11   NA   22   NA   33   NA   NA   44   55 

data

a <- structure(1:5, .Names = c("2001", "2002", "2003", "2004", "2005"
))

b <- c(`1999` = 11, `2001` = 22, `2003` = 33, `2006` = 44, `2007` = 55
)
  •  Tags:  
  • r
  • Related