Home > database >  Creating new column based on other columns in data frame in R
Creating new column based on other columns in data frame in R

Time:12-26

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.

CodePudding user response:

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