ycenycute
ycenycute

Reputation: 728

How to concat two columns into one in R

Say I have this data frame in R.

df <- data.frame( col1 = c(3,4,'NA','NA'), col2 = c('NA','NA',1,5))
  col1 col2
1    3   NA
2    4   NA
3   NA    1
4   NA    5

I would like to have new column like this

  col1 col2 col3
1    3   NA    3
2    4   NA    4
3   NA    1    1
4   NA    5    5

How shall I do that?

Upvotes: 0

Views: 3444

Answers (2)

akrun
akrun

Reputation: 887851

We can use pmax or pmin to do this (from base R)

df$col3 <- do.call(pmax, c(df, na.rm=TRUE))
df$col3 
#[1] 3 4 1 5

data

df <- structure(list(col1 = c(3L, 4L, NA, NA), col2 = c(NA, NA, 1L, 
5L)), .Names = c("col1", "col2"), class = "data.frame", row.names = c("1", 
"2", "3", "4"))

Upvotes: 0

GGamba
GGamba

Reputation: 13680

At the moment your df does not contains true NA but rather the strings 'NA'. You probably want to have true NA, as per @G5W comment.

Once we have true NA we can use:

df$col3 <- ifelse(is.na(df$col1), df$col2, df$col1)

or, with dplyr:

library(dplyr)
df$col3 <- coalesce(df$col1, df$col2)

Upvotes: 1

Related Questions