Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Row Minimum except certain columns

Tags:

r

I have a data frame below. I need to find the the row min and max except few column that are characters.

 df
  x y z
1 1 1 a
2 2 5 b
3 7 4 c 

I need

  df
  x y z  Min  Max
1 1 1 a   1    1
2 2 5 b   2    5   
3 7 4 c   4    7
like image 640
Dev P Avatar asked Nov 22 '25 03:11

Dev P


2 Answers

Another dplyr possibility could be:

df %>%
 mutate(Max = do.call(pmax, select_if(., is.numeric)),
        Min = do.call(pmin, select_if(., is.numeric)))

  x y z Max Min
1 1 1 a   1   1
2 2 5 b   5   2
3 7 4 c   7   4

Or a variation proposed be @G. Grothendieck:

df %>% 
 mutate(Min = pmin(!!!select_if(., is.numeric)), 
        Max = pmax(!!!select_if(., is.numeric)))
like image 125
tmfmnk Avatar answered Nov 24 '25 17:11

tmfmnk


Another base R solution. Subset only the columns with numbers and then use apply in each row to get the minimum and maximum value with range.

cbind(df, t(apply(df[sapply(df, is.numeric)], 1, function(x)
    setNames(range(x, na.rm = TRUE), c("min", "max")))))
#  x y z min max
#1 1 1 a   1   1
#2 2 5 b   2   5
#3 7 4 c   4   7
like image 25
d.b Avatar answered Nov 24 '25 16:11

d.b



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!