问题描述
有没有办法选择多列数据帧的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
将 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)
这篇关于返回具有多列的data.frame的pmin或pmax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!