Home > other >  Column-wise min and max in new dataframe in R
Column-wise min and max in new dataframe in R

Time:10-24

I have a dataframe like the following:

sample<-c("A", "B", "C", "D")
x<-c(1,2,7,1)
y<-c(1,5,4,2)
df <- data.frame(sample,x,y)

and my desired output should be something like this:

  x y
min 1 1
max 7 5

I tried

df_min <- apply(df[, c(2,3)], 2, FUN = min, na.rm = TRUE)
df_max <- apply(df[, c(2,3)], 2, FUN = max, na.rm = TRUE)

but how do I get that into something that looks like my desired output dataframe?

CodePudding user response:

You can use range:

data.frame(value = c("min", "max"),
           sapply(df[2:3], range))

  value x y
1   min 1 1
2   max 7 5

Or in dplyr:

df %>% 
  summarise(across(-sample, range)) %>% 
  mutate(value = c("min", "max"), .before = 1)

If you wanna stick with min and max:

data.frame(value = c("min", "max"),
           sapply(df[2:3], function(x) rbind(min(x), max(x))))

CodePudding user response:

There's a fast implementation in matrixStats::colRanges.

t(matrixStats::colRanges(as.matrix(df[, 2:3])))
#      [,1] [,2]
# [1,]    1    1
# [2,]    7    5
  • Related