Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging two columns into one in R [duplicate]

Tags:

merge

r

I have the following data frame, and am trying to merge the two columns into one, while replacing NA's with the numeric values.

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

The result I want is:

ID    New 1     3 2     2 3     4 4     1 

Thanks in advance!

like image 941
yongkornz Avatar asked Apr 14 '15 18:04

yongkornz


People also ask

How do I combine data from multiple columns into one column in R?

How do I concatenate two columns in R? To concatenate two columns you can use the <code>paste()</code> function. For example, if you want to combine the two columns A and B in the dataframe df you can use the following code: <code>df['AB'] <- paste(df$A, df$B)</code>.

How do I stack two columns in R?

Method 1: Using stack method The cbind() operation is used to stack the columns of the data frame together. Initially, the first two columns of the data frame are combined together using the df[1:2]. This is followed by the application of stack() method applied on the last two columns.


1 Answers

This probably didn't exist when the answers were written, but since I came here with the same question and found a better solution, here it is for future googlers:

What you want is the coalesce() function from dplyr:

y <- c(1, 2, NA, NA, 5) z <- c(NA, NA, 3, 4, 5) coalesce(y, z)  [1] 1 2 3 4 5 
like image 133
jzadra Avatar answered Oct 04 '22 10:10

jzadra