Vitomir
Vitomir

Reputation: 295

Compare 2 vectors and add missing values from target vector in R

I am using R and I have a correct vector whose names contain all the target names (names(correct) <- c("A","B","C","D","E")) such as:

correct <- c("a","b","c","d","e")
names(correct) <- c("A","B","C","D","E")

The vector I have to modify, instead, tofix, has names that may miss some values compared to correct above, in the example below is missing "C" and "E".

tofix <- c(2,5,4)
names(tofix) <- c("A","B","D")

So I want to fix it in a way that the resulting vector, fixed, contains the same names as in correct and with the same order, and when the name is missing adds 0 as a value, like the below:

fixed <- c(2,5,0,4,0)
names(fixed) <- names(correct)

Any idea how to do this in R? I tried with multiple if statements and for loops, but time complexity was far from ideal.

Many thanks in advance.

Upvotes: 1

Views: 198

Answers (2)

Onyambu
Onyambu

Reputation: 79228

unlist(modifyList(as.list(table(names(correct))*0), as.list(tofix)))
A B C D E 
2 5 0 4 0 

Upvotes: 1

Kra.P
Kra.P

Reputation: 15123

You may try

fixed <- rep(0, length(correct))
fixed[match(names(tofix), names(correct))] <- tofix
names(fixed) <- names(correct)
fixed

A B C D E 
2 5 0 4 0 

Upvotes: 1

Related Questions