在R中具有数据帧的每一行的最小值

时间:2021-07-30 22:54: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 each row separately. I'm sure I'm missing something really simple here? Any ideas much appreciated.

我试图在数据框中的多个列中做一个简单的最小值,但min函数自动返回整个每列的min而不是分别对每一行。我确定我错过了一些非常简单的东西吗?任何想法都非常感激。

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

4 个解决方案

#1


16  

You can use apply to go through each row

您可以使用apply来遍历每一行

apply(df, 1, FUN=min)

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

其中1表示对每行df应用FUN,2表示将FUN应用于列。

#2


2  

We could also use rowMins from library(matrixStats)

我们也可以使用库中的rowMins(matrixStats)

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

#3


2  

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.

我们可以使用pmin,它找到值集的并行最小值。由于我们的df在技术上是一个列表,我们需要通过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))

#4


0  

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

只想添加如何使用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


16  

You can use apply to go through each row

您可以使用apply来遍历每一行

apply(df, 1, FUN=min)

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

其中1表示对每行df应用FUN,2表示将FUN应用于列。

#2


2  

We could also use rowMins from library(matrixStats)

我们也可以使用库中的rowMins(matrixStats)

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

#3


2  

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.

我们可以使用pmin,它找到值集的并行最小值。由于我们的df在技术上是一个列表,我们需要通过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))

#4


0  

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

只想添加如何使用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.