我在R中设置了以下3列数据:
Year Boys Girls
2018 5000 4000
2019 5030 4050
2020 5040 4010
我如何才能找到哪个年份的男孩+女孩总数最高(使用R)?
[我在网上搜索后没有看到任何内容,向我显示了将显示总数最高的年份的代码。
要显示年份和最高总数,请使用以下代码:
df$Total <- df$Boys + df$Girls
df[which.max(df$Boys + df$Girls), c('Year', 'Total')]
[第一行添加一列Total
,其中包含男孩和女孩的总数,第二行确定最大总计数所在的行,并从中报告Year
和Total
的值行。
[tidyverse
方式
## Construct data frame
df <- tibble(Year = 2018:2020,
Boys=c(5000,5030,5040),
Girls=c(4000,4050,4010))
df %>%
mutate(Total = Boys + Girls) %>% # Add totals to the data frame
filter(Total == max(Total)) # Extract row with highest total