0

How can I recode the values NA of variable b, with the values of the row in variable a. See df with a and b: the expected output is df2.

a<- c(10, 12, 8, 7, 6)
b<-  c(5, NA, 6, NA, NA)
df <- data.frame (a,b)
df


 df
#    a  b
# 1 10  5
# 2 12 NA
# 3  8  6
# 4  7 NA
# 5  6 NA

# df2
#    a  b
# 1 10  5
# 2 12 12
# 3  8  6
# 4  7  7
# 5  6  6
Cettt
  • 11,460
  • 7
  • 35
  • 58

2 Answers2

2

You can set the NA values of column B (df$b[is.na(df$b)]) to the values of a when b is NA (df$a[is.na(df$b)])

df$b[is.na(df$b)] <- df$a[is.na(df$b)]

#    a  b
# 1 10  5
# 2 12 12
# 3  8  6
# 4  7  7
# 5  6  6
Maël
  • 45,206
  • 3
  • 29
  • 67
2

You can use simple subsetting:

df$b <- ifelse(is.na(df$b), df$a, df$b)
Cettt
  • 11,460
  • 7
  • 35
  • 58