简体   繁体   中英

Creating new column based on other columns in data frame in R

I have a data frame with three columns and four rows. I want to create a new column based on available columns such that new column gets the maximum value of the corresponding row (no matter if there is NA or not). If all are NAs, the new column gets NA. enter image description here

Thanks.

We could use pmax with na.rm specified as TRUE (assuming it is a data.frame object and the missing values are NA )

df1$new_column <- do.call(pmax, c(df1, na.rm = TRUE))

-output

> df1
   A   B   C new_column
1 98  NA  NA         98
2 NA  NA  NA         NA
3 98 100  NA        100
4 98 100 200        200

data

df1 <- data.frame(A = c(98, NA, 98, 98), B = c(NA, NA, 100, 100),
    C = c(NA, NA, NA, 200))

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