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!
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>.
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.
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
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