R dplyr rowwise mean or min and other methods?

后端 未结 5 1299
情书的邮戳
情书的邮戳 2020-12-01 19:23

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         


        
5条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 19:32

    There seems to be talk that some dplyr functions like rowwise could be deprecated in the long term (such rumblings on display here). Instead, certain functions from the map family of functions -- such as the pmap function -- from purrr can be used to perform this sort of calculation:

    library(tidyverse)
    
    df %>% mutate(Min = pmap(df, min), Mean = rowMeans(.))
    
    #              A          B           C        Min       Mean
    # 1  -1.38507062  0.3183367 -1.10363778  -1.385071 -0.7234572
    # 2   0.03832318 -1.4237989  0.44418506  -1.423799 -0.3137635
    # 3  -0.76303016 -0.4050909 -0.20495061 -0.7630302 -0.4576905
    # 4   0.21230614  0.9953866  1.67563243  0.2123061  0.9611084
    # 5   1.42553797  0.9588178 -0.13132225 -0.1313222  0.7510112
    # 6   0.74447982  0.9180879 -0.19988298  -0.199883  0.4875616
    # 7   0.70022940 -0.1509696  0.05491242 -0.1509696  0.2013907
    # 8  -0.22935461 -1.2230688 -0.68216549  -1.223069 -0.7115296
    # 9   0.19709386 -0.8688243 -0.72770415 -0.8688243 -0.4664782
    # 10  1.20715377 -1.0424854 -0.86190429  -1.042485 -0.2324120
    

    Mean is a special case (hence the use of the base function rowMeans), since mean on data.frame objects was deprecated with R 3.0.

提交回复
热议问题