1
votes

I have three values below. What I want to do is create a vector the same length as lookup, where the NA elements are given the value of replace, and the rest of the elements are given values in the corresponding position in data. E.g.

lookup = c(NA, NA, 1, 2, NA, 3, NA)
data = c("user_3", "user_4", "user_6")
replace = "no_user_data"

The desired output would then be: c("no_user_data", "no_user_data", "user_3", "user_4", "no_user_data", "user_6", "no_user_data")

The key constraint here is I would love to leverage tidyverse as much as possible. My current solution looks like this:

data <- c(data, replace)
lookup[is.na(lookup)] <- length(data)
data <- data[lookup]

which I believe with the help of some tidyverse magic could look a lot better. Thanks!

2
If you ask me tidyverse should be an answer to problems, not a problem in itself. Any particular reason why you would want to do this?mpjdem
@mpjdem - I did once see a suggestion to have add subtract etc functions so you could do 1 %>% add(2) and get 3 . We haven't reached the peak yet.thelatemail
@thelatemail Like 1 %>% `+`(2) (or 1 %>% "+"(2))Marek

2 Answers

6
votes

You can use dplyr::coalesce function, it's a nice way to replace missing values within a vector:

dplyr::coalesce(data[lookup], replace)

# [1] "no_user_data" "no_user_data" "user_3"       "user_4"       "no_user_data"
# [6] "user_6"       "no_user_data"
2
votes

We can also use replace from base R

replace(data[lookup], is.na(lookup), replace)
#[1] "no_user_data" "no_user_data" "user_3"       "user_4"       "no_user_data"
#[6] "user_6"       "no_user_data"