繁体   English   中英

dplyr加权均值会产生长度误差...如何总结加权均值?

[英]dplyr weighted mean produces length error… how to summarize weighted mean?

您如何获得加权调查结果的摘要?

每次尝试时,我都会收到一条错误消息,说长度不一样。

library(tidyverse)

x <- tbl_df(data.frame("Age" = c(21,21,15,15,22,22,47,47,42,42,33,33,32,32), 
"survey answer 1-10 scale" = c(1,10,3,6,5,4,8,1,10,3,6,5,4,8), 
"weight" =c(.7,.8,.9,1,1.1,1.2,1.3,.7,.8,.9,1,1.1,1.2,1.3)))

print(x)

# # A tibble: 14 x 3
#      Age survey.answer.1.10.scale weight
#    <dbl>                    <dbl>  <dbl>
#  1    21                        1    0.7
#  2    21                       10    0.8
#  3    15                        3    0.9
#  4    15                        6    1  
#  5    22                        5    1.1
#  6    22                        4    1.2
#  7    47                        8    1.3
#  8    47                        1    0.7
#  9    42                       10    0.8
# 10    42                        3    0.9
# 11    33                        6    1  
# 12    33                        5    1.1
# 13    32                        4    1.2
# 14    32                        8    1.3



x %>%
    group_by(Age) %>%
    summarise(weighted.mean(., w=.$weight, na.rm=TRUE))

哪个返回:

Error in summarise_impl(.data, dots) : 
Evaluation error: 'x' and 'w' must have the same length.

另一个答案是说加权意味着只对矩阵起作用? 但这没有意义。 即使我尝试,也没有bueno:

as.matrix(x)->mat.rx
mat.rx %>%
group_by(Age) %>%
    summarise(weighted.mean(., w=.$weight, na.rm=TRUE))

返回:

Error in UseMethod("group_by_") : 
  no applicable method for 'group_by_' applied to an object of class "c('matrix'
, 'double', 'numeric')"
library(tidyverse)

x <- tbl_df(data.frame("Age" = c(21,21,15,15,22,22,47,47,42,42,33,33,32,32), 
"survey answer 1-10 scale" = c(1,10,3,6,5,4,8,1,10,3,6,5,4,8), 
"weight" =c(.7,.8,.9,1,1.1,1.2,1.3,.7,.8,.9,1,1.1,1.2,1.3)))

x %>% 
    group_by(Age) %>%
    summarise(weighted.mean(survey.answer.1.10.scale, w=weight, na.rm=TRUE))
# A tibble: 7 x 2
    Age `weighted.mean(survey.answer.1.10.scale, w = weight, na.rm = TRUE)`
  <dbl>                                                               <dbl>
1    15                                                                4.58
2    21                                                                5.8 
3    22                                                                4.48
4    32                                                                6.08
5    33                                                                5.48
6    42                                                                6.29
7    47                                                                5.55

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM