Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filling in empty elements on a vector from another vector by position [R]

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading