Combine two vectors of different lengths based on common values ​​and increase the brevity

I have two vectors with some values, but with different lengths:

x <- 1:10
# [1]  1  2  3  4  5  6  7  8  9 10

y <- c(3, 5, 8)
# [1]  3  5 8

I would like to combine these two vectors in a dataframe and get the following result:

data.frame(big = x,
           small = c(NA, NA,  3, NA,  5, NA, NA,  8, NA, NA))
#    big small
# 1    1    NA
# 2    2    NA
# 3    3     3
# 4    4    NA
# 5    5     5
# 6    6    NA
# 7    7    NA
# 8    8     8
# 9    9    NA
# 10  10    NA
+4
source share
1 answer

One possibility is to index the short vector using matchbetween long and short, with the argument nomatchset to NA("the value to be returned if no match is found").

data.frame(big = x,
           small = y[match(x, y, nomatch = NA)])
+5
source

Source: https://habr.com/ru/post/1668141/


All Articles