如何使用dplyr获得多个变量的pmax? [英] How to get pmax over multiple variables with dplyr?

查看:112
本文介绍了如何使用dplyr获得多个变量的pmax?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在有人将此问题标记为重复之前,我已经看到过此一个,但并不能解决我的问题.如果我尝试

Before someone marks this question as duplicate, I have already seen this one and it does not solve my question. If I try

mtcars %>% mutate(new = rowMeans(select(.,c(1,7)), na.rm = TRUE))

它工作得很好,但是如果我使用 pmax 而不是 rowMeans :

it works nicely, but if I do the same with pmax instead of rowMeans:

mtcars %>% mutate(new = pmax(select(.,c(1,7)), na.rm = TRUE))

我知道

Error: Column `new` is of unsupported class data.frame

为什么?在此示例中,我可以使用

Why? In this example, I can get the output with

mtcars %>% mutate(new = pmax(mpg,qsec,carb,na.rm = TRUE))

但是我尝试使用 select ,因为我需要一些 select辅助器或由列位置确定的变量(例如 1,7 ),否则我也会收到错误消息.

but I try to use select since I need for my real data either some select helper or variables determined by column position (like 1,7 in the example), and otherwise I also get errors.

正如链接问题的答案中所建议的那样,我也尝试使用 do.call 来获取错误.

As suggested in an answer in the linked question I also tried to use do.call obtaining an error too.

谢谢!

推荐答案

使用 do.call ,我们可以评估 pmax 而无需指定变量,即

Using do.call we can evaluate pmax without specifying the variables, i.e.

mtcars %>% 
  mutate(new = do.call(pmax, c(select(., c(1, 7)), na.rm = TRUE)))

#    mpg cyl  disp  hp drat    wt  qsec vs am gear carb   new
#1  21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4 21.00
#2  21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4 21.00
#3  22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1 22.80
#4  21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1 21.40
#5  18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2 18.70
#6  18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1 20.22
#7  14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4 15.84
#...

这篇关于如何使用dplyr获得多个变量的pmax?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆