首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Weighted.Mean中的错误。为什么找不到专栏?

Weighted.Mean中的错误。为什么找不到专栏?
EN

Stack Overflow用户
提问于 2021-05-25 11:45:25
回答 1查看 89关注 0票数 2

我有一张像这样的数据

代码语言:javascript
复制
df <- data.frame(Region = c("Asia","Asia","Africa","Europe","Europe"),
Emp = c(120,40,10,67,110),
Sales18 = c(12310, 4510, 1140, 5310, 16435),
Sales19 = c(15670, 6730, 1605, 6120, 1755))

我正在运行一个代码,在该代码中,我按区域分组,然后根据'Emp‘对所有“销售”列取平均值和加权平均值。

代码语言:javascript
复制
Result <- df %>% group_by(Region) %>% 
summarise(sales18 = mean(Sales18, na.rm = T),
sales19 = mean(Sales19, na.rm = T),
weightedsales18 = weighted.mean(Sales18, .data[[Emp]], na.rm = T),
weightedsales19 = weighted.mean(Sales19, .data[[Emp]], na.rm = T))

但是,我得到了以下错误

代码语言:javascript
复制
Error in splice(dot_call(capture_dots, frame_env = frame_env, named = named,  : 
  object 'Emp' not found

不知道我做错了什么

EN

回答 1

Stack Overflow用户

发布于 2021-05-25 12:01:39

未引用的Emp of [[告诉R搜索名为Emp的字符串变量,该变量可能包含包含权重的其他变量的名称,如下所示:

代码语言:javascript
复制
df <- data.frame(Region = c("Asia","Asia","Africa","Europe","Europe"),
             x = c(120,40,10,67,110),
             Sales18 = c(12310, 4510, 1140, 5310, 16435),
             Sales19 = c(15670, 6730, 1605, 6120, 1755))

Emp <- 'x'

df %>% group_by(Region) %>% 
  summarise(sales18 = mean(Sales18, na.rm = T),
            sales19 = mean(Sales19, na.rm = T),
            weightedsales18 = weighted.mean(Sales18, .data[[Emp]], na.rm = T),
            weightedsales19 = weighted.mean(Sales19, .data[[Emp]], na.rm = T))

# A tibble: 3 x 5
  Region sales18 sales19 weightedsales18 weightedsales19
  <chr>    <dbl>   <dbl>           <dbl>           <dbl>
1 Africa   1140    1605            1140            1605 
2 Asia     8410   11200           10360           13435 
3 Europe  10872.   3938.          12224.           3407.

因为,您没有这种Emp,所以R会抛出一个错误。

该怎么办呢?只需引用Emp inside [[

代码语言:javascript
复制
df <- data.frame(Region = c("Asia","Asia","Africa","Europe","Europe"),
                 Emp = c(120,40,10,67,110),
                 Sales18 = c(12310, 4510, 1140, 5310, 16435),
                 Sales19 = c(15670, 6730, 1605, 6120, 1755))


df %>% group_by(Region) %>% 
  summarise(sales18 = mean(Sales18, na.rm = T),
            sales19 = mean(Sales19, na.rm = T),
            weightedsales18 = weighted.mean(Sales18, .data[['Emp']], na.rm = T),
            weightedsales19 = weighted.mean(Sales19, .data[['Emp']], na.rm = T))

# A tibble: 3 x 5
  Region sales18 sales19 weightedsales18 weightedsales19
  <chr>    <dbl>   <dbl>           <dbl>           <dbl>
1 Africa   1140    1605            1140            1605 
2 Asia     8410   11200           10360           13435 
3 Europe  10872.   3938.          12224.           3407.
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67687277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档