How do I combine two columns and replace missing values in R?
Let's say I have a data.frame:
D = data.frame(a = c(1,NA,3), b = c(1,2,NA))
Looks like this
a b
1 1 1
2 NA 2
3 3 NA
How would I get it to look like this:
c
1 1
2 2
3 3
Assuming the two columns will either have the same values or one of them will be NA
D = data.frame(a = c(1,NA,3), b = c(1,2,NA))
D[['c']] <- rowMeans(D, na.rm = TRUE)
D
a b c
1 1 1 1
2 NA 2 2
3 3 NA 3
If Column a is the master column and you want to copy values in b that are NA in a then:
D = data.frame(a = c(1,NA,3), b = c(1,2,NA))
D2=data.frame(c = D$a)
D2$c[is.na(D2$c)] <- D$b[is.na(D$a)]
D2
c
1 1
2 2
3 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.