Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

r - Combine/merge columns while avoiding NA?

I have a really simple problem but haven't been able to find a solution. I am hoping someone can help. I have a dataframe test3:

test3 <- structure(list(A = c(1L, 2L, NA, 4L), B = c(NA, NA, 3L, NA)), .Names = c("A", 
"B"), class = "data.frame", row.names = c(NA, -4L))


    A   B
1   1   NA
2   2   NA
3   NA  3
4   4   NA

and I would like to combine/merge the columns A and B into a third column C to give

    A   B   C
1   1   NA  1
2   2   NA  2
3   NA  3   3
4   4   NA  4

This seems like a very common problem with a simple solution, yet I can't find a solution in my searches of stackoverflow or google. Can anyone point me in the right direction?

EDIT: My example above shows only two columns, but I will be working in a much larger dataframe with many more columns (yet I will still need to combine only two columns). If anyone could recommend a general solution to merge two columns in a big dataframe, i'd appreciate it!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's one approach:

> transform(test3, C=rowSums(test3, na.rm=TRUE))
   A  B C
1  1 NA 1
2  2 NA 2
3 NA  3 3
4  4 NA 4

Consider the following data.frame test3 with an additional column AA, you can use the operator [ to subet the columns you are interested in:

> set.seed(1) # adding a new column
> test3$AA <- rnorm(4, 10, 1)
> test3  # this is how test3 looks like
   A  B        AA
1  1 NA  9.373546
2  2 NA 10.183643
3 NA  3  9.164371
4  4 NA 11.595281
> transform(test3, C=rowSums(test3[, c("A", "B")], na.rm=TRUE))
   A  B        AA C
1  1 NA  9.373546 1
2  2 NA 10.183643 2
3 NA  3  9.164371 3
4  4 NA 11.595281 4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...