Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

row - R dplyr rowwise mean or min and other methods?

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)

I've tried

mydataframe %>% rowwise() %>% mean

or

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

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

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.

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) 

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

Thanks

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))
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...