【问题标题】:Using weighted.mean() in mutate() to create rowwise weighted means在 mutate() 中使用 weighted.mean() 创建行加权平均值
【发布时间】:2021-09-29 07:09:58
【问题描述】:

我正在努力创建一个新列,该列应构造为 X 和 Y 变量的行加权平均值。我想使用 weighted.mean() 的原因是我需要的 na.rm 功能。

我有数据框

library(tidyverse)
seed(2021)

df <- tibble(x = rnorm(10,0,5),
             y = rnorm(10,0,10))

我尝试像这样创建新列:

df <- df %>% mutate(z = weighted.mean(cbind(x,y),cbind(rep(c(0.2,0.8),10))))

但是,这会产生一个填充相同常量的行,所以我似乎没有指定我需要逐行操作。我将不胜感激指导手 - 谢谢!

/F

【问题讨论】:

    标签: r tidyverse dplyr


    【解决方案1】:

    试试这个方法

    df <- tibble(x = rnorm(10,0,5),
                 y = rnorm(10,0,10))
    
    df$z <- df %>% 
      rowwise %>%
      do(data.frame(
        z = weighted.mean(
          x = c(.$x, .$y),
          w = c(.2, .8)
        )
      )) %>%
      ungroup %>%
      magrittr::use_series("z")
    

    或

    df %>% 
      mutate( z= df %>% 
                rowwise %>% 
                do(data.frame(
        z = weighted.mean(
          x = c(.$x, .$y),
          w = c(.2, .8)
        )
      )))
      
    
                x       y     z
        <dbl>   <dbl>   <dbl>
     1  0.176  -1.95   -1.52 
     2 -3.33   -6.88   -6.17 
     3 -4.08    0.827  -0.154
     4  0.609   1.68    1.47 
     5  0.327   8.06    6.51 
     6 -8.63   -2.12   -3.42 
     7 -4.68   -8.52   -7.76 
     8  6.49  -13.0    -9.07 
     9 -2.95  -25.4   -20.9  
    10  2.78    5.36    4.85
    

    【讨论】:

      【解决方案2】:

      你可以做-

      library(dplyr)
      
      df %>%
        rowwise() %>%
        mutate(z = weighted.mean(c(x,y), c(0.8, 0.2))) %>%
        ungroup
      
      #      x      y      z
      #     <dbl>  <dbl>  <dbl>
      # 1 -0.612  -10.8   -2.65
      # 2  2.76    -2.73   1.66
      # 3  1.74     1.82   1.76
      # 4  1.80    15.1    4.46
      # 5  4.49    16.0    6.80
      # 6 -9.61   -18.4  -11.4 
      # 7  1.31    16.2    4.29
      # 8  4.58     1.31   3.93
      # 9  0.0689  14.8    3.02
      #10  8.65    15.1    9.95
      

      或者在基础 R 中 -

      df$z <- apply(df, 1, function(x) weighted.mean(x, c(0.8, 0.2)))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多