I have a column with several NA's that I want to be replaced by values from other columns of the same data frame. Here's an example
test <- tibble(x = c(1,2,NA,NA,5,NA,3), y1 = c(NA,NA,3,NA,NA,NA,NA), y2 = c(NA,NA,NA,15,NA,1,NA) )
Ideally I want x to be (1,2,3,15,5,1,3). The easiest way I can find that does this is to use the
coalesce() function, so essentially I would do
test %>% mutate(x = coalesce(x,y1,y2)). That said, for my specific data set I have the following problems:
- There are more than two columns to take values from, i.e. instead of having just y1 and y2 in the above example, I have a lot more columns.
- The names of the columns to take values from have very weird names with little patterns.
In other words, instead of having to write
y1,y2 in the
coalesce() function above, I would like to somehow call them without specifying them. Any idea how this can be achieved? Many thanks!