Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

r - Return pmin or pmax of data.frame with multiple columns

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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) 

is thus equivalent to:

pmax(dat$a, dat$b)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...