You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用R汇总Wild_animals数据框年度数量并识别非100的年份列

处理Wild_animals数据集:计算年份总和并识别异常年份

原始数据集

现有名为Wild_animals的DataFrame,数据结构如下:

# 构建示例数据集
Wild_animals <- tibble::tibble(
  Animal = c("Cat", "Dog", "Fox", "Tiger", "Lion"),
  `2000` = c(25, 25, 25, 10, 5),
  `2001` = c(40, 15, 12, 21, 7),
  `2002` = c(20, 20, 20, 20, 20),
  `2003` = c(0, 0, 0, 0, 100),
  `2004` = c(51, 48, 0, 0, 1),
  `2005` = c(15, 46, 15, 15, 40),
  `2006` = c(85, 5, 5, 1, 4),
  `2007` = c(0, 0, 0, 0, 0)
)

计算各年份动物总数量

提供两种实现方式,任选其一即可:

方式1:基础R实现

# 计算年份列的总和(排除Animal列)
year_totals <- colSums(Wild_animals[, -1])
# 转换为目标tibble格式
year_totals_tbl <- tibble::as_tibble_row(year_totals)

# 输出结果
year_totals_tbl

执行后得到目标结果:

# A tibble: 1 × 8
  `2000` `2001` `2002` `2003` `2004` `2005` `2006` `2007`
   <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
1     90     95    100    100    100    131    100      0

方式2:tidyverse(dplyr)实现

library(dplyr)

year_totals_tbl <- Wild_animals %>%
  summarize(across(-Animal, sum))

# 输出结果
year_totals_tbl

执行后得到与上述一致的结果。

识别总数量不等于100的年份

方式1:基础R实现

# 筛选出总和不等于100的年份名称
abnormal_years <- names(year_totals)[year_totals != 100]

# 输出结果
abnormal_years

输出:

[1] "2000" "2001" "2005" "2007"

方式2:tidyverse实现

abnormal_years_tbl <- year_totals_tbl %>%
  pivot_longer(everything(), names_to = "Year", values_to = "Total") %>%
  filter(Total != 100)

# 输出结果
abnormal_years_tbl

执行后得到结构化的异常年份数据:

# A tibble: 4 × 2
  Year  Total
  <chr> <dbl>
1 2000     90
2 2001     95
3 2005    131
4 2007      0

内容的提问来源于stack exchange,提问作者Sara Dwindler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 05:20:27