简体   繁体   中英

how to combine some columns?

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

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.

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.

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))

data

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM