问题描述
有没有办法选择具有多个列的数据框的pmax / pmin?
Is there a way to select the pmax/pmin of a data frame with multiple columns??
我只想返回最大或最小值,而不是整行
I want only the max or min returned, not the entire row.
max <- tail(df, n=1)
max
# v1 v2 v3 v4 v5 v6 v7 v8
#2014-10-03 17:35:00 58.91 45.81 33.06 70.76 36.39 45.53 33.52 34.36
pmax(max)
# v1 v2 v3 v4 v5 v6 v7 v8
#2014-10-03 17:35:00 58.91 45.81 33.06 70.76 36.39 45.53 33.52 34.36
对于这一行,我希望返回值为:
For this row, I expect a return value of :
70.76
...因为它是所有列的最大值。
...as it is the maximum value across all the columns.
推荐答案
使用 do.call
调用 pmax
将每个列的所有列进行比较行值,例如:
Use do.call
to call pmax
to compare all the columns together for each row value, e.g.:
dat <- data.frame(a=1:5,b=rep(3,5))
# a b
#1 1 3
#2 2 3
#3 3 3
#4 4 3
#5 5 3
do.call(pmax,dat)
#[1] 3 3 3 4 5
当您直接在整个data.frame上调用 pmax
时,它只有一个参数传递给函数,没有什么可以与之进行比较。所以,它只返回提供的参数,因为它必须是最大值。它适用于非数字和数字参数,即使可能没有什么意义:
When you call pmax
on an entire data.frame directly, it only has one argument passed to the function and nothing to compare it to. So, it just returns the supplied argument as it must be the maximum. It works for non-numeric and numeric arguments, even though it may not make much sense:
pmax(7)
#[1] 7
pmax("a")
#[1] "a"
pmax(data.frame(1,2,3))
# X1 X2 X3
#1 1 2 3
code> do.call(pmax,...)与data.frame意味着您将data.frame的每一列作为参数列表传递到 pmax
:
Using do.call(pmax,...)
with a data.frame means you pass each column of the data.frame as a list of arguments to pmax
:
do.call(pmax,dat)
相当于:
pmax(dat$a, dat$b)
这篇关于R:返回具有多个列的data.frame的pmin或pmax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!