R dplyr rowwise是平均还是min等方法? [英] R dplyr rowwise mean or min and other methods?

查看:633
本文介绍了R dplyr rowwise是平均还是min等方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用dplyr获取数据框架中每行的最小值(或平均值)?
我的意思是与

How can I get with dplyr the minimum (or mean) value of each row on a data.frame? I mean the same result as

apply(mydataframe, 1, mean) 
apply(mydataframe, 1, min)

我尝试过

mydataframe %>% rowwise() %>% mean

mydataframe %>% rowwise() %>% summarise(mean)

或其他组合,但我总是收到错误,我不知道正确的方式。

or other combinations but I always get errors, I don't know the proper way.

我知道我也可以使用rowMeans,但没有简单的rowMin等效。
还存在一个matrixStats包,但大多数函数不接受data.frames,只有矩阵。

I know that I could also use rowMeans, but there is no simple "rowMin" equivalent. There also exist a matrixStats package but most functions don't accept data.frames, only matrixes.

如果我想计算min rowwise,我可以使用

do.call(pmin,mydataframe)
有没有什么简单的这样的rowwise的意思?

If I want to calculate the min rowwise I could use
do.call(pmin, mydataframe) Is there anything simple like this for the rowwise mean?

do.call(mean, mydataframe) 

不行,我想我需要一个pmean函数或更复杂的东西。

doesn't work, I guess I need a pmean function or something more complex.

谢谢

为了比较结果,我们都可以工作同样的例子:

In order to compare the results we could all work on the same example:

set.seed(124)
df <- data.frame(A=rnorm(10), B=rnorm(10), C=rnorm(10))


推荐答案

我想这是你想要完成的:

I suppose this is what you were trying to accomplish:

df <- data.frame(A=rnorm(10), B=rnorm(10), C=rnorm(10))

library(dplyr)
df %>% rowwise() %>% mutate(Min = min(A, B, C), Mean = mean(c(A, B, C)))

#             A          B           C        Min        Mean
# 1   1.3720142  0.2156418  0.61260582  0.2156418  0.73342060
# 2  -1.4265665 -0.2090585 -0.05978302 -1.4265665 -0.56513600
# 3   0.6801410  1.5695065 -2.70446924 -2.7044692 -0.15160724
# 4   0.0335067  0.8367425 -0.83621791 -0.8362179  0.01134377
# 5  -0.2068252 -0.2305140  0.23764322 -0.2305140 -0.06656532
# 6  -0.3571095 -0.8776854 -0.80199141 -0.8776854 -0.67892877
# 7   1.0667424 -0.6376245 -0.41189564 -0.6376245  0.00574078
# 8  -1.0003376 -1.5985281  0.90406055 -1.5985281 -0.56493504
# 9  -0.8218494  1.1100531 -1.12477401 -1.1247740 -0.27885677
# 10  0.7868666  0.6099156 -0.58994138 -0.5899414  0.26894694

这篇关于R dplyr rowwise是平均还是min等方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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