If I have a vector like this with empty elements:
vec_empty_element <- c("z", "a", "", "")
Then I have another vector like this which will always be the same length:
needed_names <- c("x + y", "x/2", "y", "x")
How do I replace the empty element in vec_empty_element with a value from needed_names that is in the same position?
This is what I wanted to end up with:
desired_vec <- c("z", "a", "y", "x")
>Solution :
One option is to convert the blank ("" to NA and then coalesce
library(dplyr)
coalesce(na_if(vec_empty_element, ""), needed_names)
[1] "z" "a" "y" "x"
or in base R with ifelse
ifelse(nzchar(vec_empty_element), vec_empty_element, needed_names)
[1] "z" "a" "y" "x"