[英]Combine two columns in R
How do I combine two columns and replace missing values in R? 如何合并两列并替换R中的缺失值?
Let's say I have a data.frame: 假设我有一个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 假设这两列要么具有相同的值,要么其中之一为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: 如果列a是主列,并且您要复制b中a为NA的值,则:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.