how do you create new fields based on min vals and column values in r?

Here is an option with dplyr where we get the ‘MinHeader’ based on the max.col index for each row after changing the numeric values to negative, then we use rowMeans and pmin to get the mean and min per row

library(dplyr)
library(purrr)
df1 %>%
  mutate(MinHeader = names(.)[-1][max.col(-.[-1])], 
          Avg = rowMeans(.[2:4], na.rm = TRUE), 
          Min = invoke(pmin, .[2:4])) 

-output

# ID  One  Two Three MinHeader       Avg  Min
#1  A 0.60 0.40  0.20     Three 0.4000000 0.20
#2  B 0.20 0.32  0.12     Three 0.2133333 0.12
#3  C 0.10 0.24  0.14       One 0.1600000 0.10
#4  D 0.62 0.12  0.19       Two 0.3100000 0.12

data

df1 <- structure(list(ID = c("A", "B", "C", "D"), One = c(0.6, 0.2, 
0.1, 0.62), Two = c(0.4, 0.32, 0.24, 0.12), Three = c(0.2, 0.12, 
0.14, 0.19)), class = "data.frame", row.names = c(NA, -4L))

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top