min for each row with dataframe in R

后端 未结 4 1394
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 12:15

I\'m try to do a simple minimum across multiple columns in a data frame but the min function automatically returns the min across the whole of each column rather than for ea

相关标签:
4条回答
  • 2020-11-29 12:35

    You can use apply to go through each row

    apply(df, 1, FUN=min)
    

    Where 1 means to apply FUN to each row of df, 2 would mean to apply FUN to columns.

    0 讨论(0)
  • 2020-11-29 12:41

    We could use pmin, which finds the parallel minima of sets of values. Since our df is technically a list, we will need to run it via do.call.

    df$min <- do.call(pmin, df)
    

    which gives

    df
    #   x y min
    # 1 1 1   1
    # 2 2 5   2
    # 3 7 4   4
    

    Data:

    df <- data.frame(x = c(1, 2, 7), y = c(1, 5, 4))
    

    Furthermore, if na.rm = TRUE is needed, you can do

    df$min <- do.call(pmin, c(df, na.rm = TRUE))
    
    0 讨论(0)
  • 2020-11-29 12:52

    We could also use rowMins from library(matrixStats)

    library(matrixStats)
    df$minIwant <- rowMins(as.matrix(df))
    
    0 讨论(0)
  • 2020-11-29 12:54

    Just want to add on how you can also do this with dplyr.

    library(dplyr)
    
    x<-c(1,2,7)
    y<-c(1,5,4)
    df <- data.frame(x,y)
    
    df %>% rowwise() %>% mutate(minIget = min(x, y))
    # A tibble: 3 x 3
        x     y   minIget
      <dbl> <dbl>   <dbl>
    1    1.    1.      1.
    2    2.    5.      2.
    3    7.    4.      4.
    
    0 讨论(0)
提交回复
热议问题