1

library(tidyverse)

reprex for you to reproduce:

library(tidyverse)

tibble(
  x1 = c(1, 2, NA, NA, 5),
  y1 = c(4, 3, NA, NA, 7),
  x2 = c(NA, NA, 6, 7, NA),
  y2 = c(NA, NA, 2, 4, NA),
  replace1 = c("A", "B", "C", "D", "E"),
  replace2 = c("F", "G", "H", "I", "J")
)

I have this dataframe:

# A tibble: 5 x 6
     x1    y1    x2    y2 replace1 replace2
  <dbl> <dbl> <dbl> <dbl> <chr>    <chr>   
1     1     4    NA    NA A        F       
2     2     3    NA    NA B        G       
3    NA    NA     6     2 C        H       
4    NA    NA     7     4 D        I       
5     5     7    NA    NA E        J

I need the dataframe to be like this, which tidyverse pipeline will get me that?.

# A tibble: 5 x 6
  x1    y1    x2    y2    replace1 replace2
  <chr> <chr> <chr> <chr> <chr>    <chr>   
1 1     4     A     F     A        F       
2 2     3     B     G     B        G       
3 C     H     6     2     C        H       
4 D     I     7     4     D        I       
5 5     7     E     J     E        J 
0

2 Answers 2

1

We can use

library(dplyr)
library(stringr)
df1 %>% 
     mutate(across(1:4, ~ coalesce(as.character(.), 
        get(str_replace(cur_column(), "\\D+", "replace")))))

-output

# A tibble: 5 x 6
#  x1    y1    x2    y2    replace1 replace2
#  <chr> <chr> <chr> <chr> <chr>    <chr>   
#1 1     4     F     F     A        F       
#2 2     3     G     G     B        G       
#3 C     C     6     2     C        H       
#4 D     D     7     4     D        I       
#5 5     7     J     J     E        J       

Or if it is based on 'x', 'y'

 df1 %>% 
     mutate(replace_x = replace1, replace_y = replace2) %>% 
     mutate(across(1:4, ~ coalesce(as.character(.), 
         get(str_replace(cur_column(), "(\\D+)\\d+", "replace_\\1"))))) %>%   
     select(-matches('replace_[xy]'))
# A tibble: 5 x 6
#  x1    y1    x2    y2    replace1 replace2
#  <chr> <chr> <chr> <chr> <chr>    <chr>   
#1 1     4     A     F     A        F       
#2 2     3     B     G     B        G       
#3 C     H     6     2     C        H       
#4 D     I     7     4     D        I       
#5 5     7     E     J     E        J       
Sign up to request clarification or add additional context in comments.

Comments

1

Not tidy but a base R option with apply.

cols <- grep('replace', names(df))
df[] <- trimws(t(apply(df, 1, function(x) {x[is.na(x)] <- x[cols];x})))

#   x1    y1    x2    y2  replace1 replace2
#  <chr> <chr> <chr> <chr> <chr>    <chr>   
#1 1     4     A     F     A        F       
#2 2     3     B     G     B        G       
#3 C     H     6     2     C        H       
#4 D     I     7     4     D        I       
#5 5     7     E     J     E        J     

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.