0

I need to put the value of variable "A" in place of the NA of variable "B".
Example of my dataframe:

> df <- data.frame(A = seq(1, 10), B = c(1, NA, 3, 4, NA, NA, 7, 8, NA, NA))
> df
    A  B
1   1  1
2   2 NA
3   3  3
4   4  4
5   5 NA
6   6 NA
7   7  7
8   8  8
9   9 NA
10 10 NA

I want the above dataframe converted into this:

> df
    A  B
1   1  1
2   2  2
3   3  3
4   4  4
5   5  5
6   6  6
7   7  7
8   8  8
9   9  9
10 10 10

3 Answers3

2

Using R base indexing

> df$B[is.na(df$B)] <- df$A[is.na(df$B)]
> df
    A  B
1   1  1
2   2  2
3   3  3
4   4  4
5   5  5
6   6  6
7   7  7
8   8  8
9   9  9
10 10 10
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
2

Use coalesce

library(dplyr)
df <- df %>%
     mutate(B = coalesce(B, A))

-output

df
 A  B
1   1  1
2   2  2
3   3  3
4   4  4
5   5  5
6   6  6
7   7  7
8   8  8
9   9  9
10 10 10
akrun
  • 874,273
  • 37
  • 540
  • 662
2

I prefer coalesce. Here is one with an ifelse:

library(dplyr)
df %>% 
  mutate(B = ifelse(is.na(B), A, B))
   A  B
1   1  1
2   2  2
3   3  3
4   4  4
5   5  5
6   6  6
7   7  7
8   8  8
9   9  9
10 10 10
TarJae
  • 72,363
  • 6
  • 19
  • 66