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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With