Min for each row with a data frame in R

I'm trying to make a simple minimum for several columns in a data frame, but the min function automatically returns min for the entire column, and not for each row separately. I'm sure I'm missing something really simple here? Any ideas are greatly appreciated.

x<-c(1,2,7)
y<-c(1,5,4)
minIwant <- c(1,2,4)
df <- data.frame(x,y,minIwant)
df$minIget <- min(df$x,df$y)
df
  x y minIwant minIget
1 1 1        1       1
2 2 5        2       1
3 7 4        4       1
+10
source share
4 answers

You can use applyto go through each line

apply(df, 1, FUN=min)

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

+19
source

pmin, . df , do.call.

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

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

:

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

, na.rm = TRUE,

df$min <- do.call(pmin, c(df, na.rm = TRUE))
+3

We could also use rowMinsfromlibrary(matrixStats)

library(matrixStats)
df$minIwant <- rowMins(as.matrix(df))
+2
source

I just want to add how you can 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.
+1
source

Source: https://habr.com/ru/post/1623464/


All Articles