Home > Software engineering >  fill empty vector by matching index and year in R
fill empty vector by matching index and year in R

Time:11-28

I want to fill empty vector by matching year with index. For example, say I am analyzing 18 years of data. I have a vector consisting of dates in %Y-%m format for eg.

vt = c("2004-02","2006-03","2007-07")

I have a vector with NA say

vv = rep(NA, 18)

now I want to fill the empty vector in a way that "2004-02" goes to 4th position, "2006-03" goes to 6th position, and "2007-07" goes to 7th position in the empty vector. I want to fill the empty vector by matching the position with the year.

I can do it by looping over the date vector but I want a vectorize way to do this.

expected output

NA NA NA 2004-02 NA 2006-03 2007-07 NA NA NA NA NA NA NA NA NA NA NA

I will really appreciate any help.

CodePudding user response:

This does what the post wants as an output, but might not cover all the edge cases required.

vt = c("2004-02","2006-03","2007-07")
vv <- rep(NA_character_, 18)
ids <- as.integer(substr(vt, 4, 4))
vv[ids] <- vt
vv

However, note that this depends on unique years being provided, overwriting the last occurrence. That is,

vt = c("2004-02","2006-03","2007-07", "2007-01")

Will give somewhat misleading results. Another note: The year 2000 will throw an error. If there are such cases, as.integer(substr(vt, 4, 4)) 1 could be used (on a length 19 vector).

CodePudding user response:

vt <- c("2004-02","2006-03","2007-07")
vv <- rep(NA, 18)

vv[as.numeric(sapply(strsplit(vt, "-"), `[`, 1))-2000] <- vt
  •  Tags:  
  • r
  • Related