Reputation:
I have 3 columns as below:
col1 col2 col3
1 NA NA
NA 3 NA
NA NA NA
3 NA NA
how I can combine these 3 column and make a new one?
col1 col2 col3 new
1 NA NA 1
NA 3 NA 3
NA NA NA NA
3 NA NA 3
Notice they don't have intersection, meaning that if one of them is a number 2 others are NA
Upvotes: 1
Views: 38
Reputation: 887831
We can also use coalesce
from dplyr
library(dplyr)
df1 %>%
mutate(new = coalesce(col1, col2, col3))
# col1 col2 col3 new
#1 1 NA NA 1
#2 NA 3 NA 3
#3 NA NA NA NA
#4 3 NA NA 3
or instead of specifying the column names
df1 %>%
mutate(new = coalesce(!!! .))
Or with reduce
library(purrr)
df1 %>%
mutate(new = reduce(., coalesce))
df1 <- structure(list(col1 = c(1L, NA, NA, 3L), col2 = c(NA, 3L, NA,
NA), col3 = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_
)), row.names = c(NA, -4L), class = "data.frame")
Upvotes: 0
Reputation: 389235
We can use max.col
to get the non-NA value in each row.
df$new <- df[cbind(seq_len(nrow(df)), max.col(!is.na(df)))]
df
# col1 col2 col3 new
#1 1 NA NA 1
#2 NA 3 NA 3
#3 NA NA NA NA
#4 3 NA NA 3
If you more than 1 value which is not not NA in a row you might want to look into ties.method
of max.col
based on your requirement.
Upvotes: 0
Reputation: 4284
Let's say your dataframe is called df
,
df$new <- pmin(df$col1,df$col2,df$col3,na.rm=TRUE)
should answer your question.
The pmin
function get the minimum of the three columns of each row, and the na.rm=TRUE
ignores the NA values, so if by row you only have at most one non NA value this should work.
Upvotes: 4