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

Time:04-07

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")

CodePudding user response:

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"

CodePudding user response:

Using nzchar:

vec_empty_element <- c("z", "a", "", "")
needed_names <-  c("x   y", "x/2", "y", "x")

vec_empty_element[!nzchar(vec_empty_element)] <- needed_names[!nzchar(vec_empty_element)]
# [1] "z" "a" "y" "x"

CodePudding user response:

You can also use a simple index:

vec_empty_element[vec_empty_element == ""] <- needed_names[vec_empty_element == ""]

#[1] "z" "a" "y" "x"

Or with ifelse

vec_empty_element <- ifelse(vec_empty_element == "", needed_names, vec_empty_element)
  •  Tags:  
  • r
  • Related