简体   繁体   English

如何在 R 中计算特定条件下的平均值?

[英]How do i calculate the average with certain condition in R?

I've been trying to calculate the average of a column with condition in a dataframe and plot it in a graph.我一直在尝试计算数据框中具有条件的列的平均值并将其绘制在图表中。 But so far I can only get the average of the whole column with mean(df$Age) .但到目前为止,我只能用mean(df$Age)获得整列的mean(df$Age) Sample dataframe示例数据框

What I'm trying to get is the average age of employees in Vancouver but I'm not sure how to do it so I can't plot it out.我想得到的是温哥华员工的平均年龄,但我不知道该怎么做,所以我无法绘制出来。

library(tidyverse)
tribble(
  ~Age, ~City,
  61, "Vancouver",
  58, "Vancouver",
  48, "Terrace",
  48, "Terrace"
) %>%
  group_by(City) %>%
  summarise(Age = mean(Age))
#> # A tibble: 2 x 2
#>   City        Age
#>   <chr>     <dbl>
#> 1 Terrace    48  
#> 2 Vancouver  59.5

Created on 2021-11-12 by the reprex package (v2.0.1)reprex 包(v2.0.1) 于 2021 年 11 月 12 日创建

要获得特定城市的平均值,您可以对其进行子集化并取mean

result <- mean(df$Age[df$CityName == 'Vancouver'], na.rm = TRUE)

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

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