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

在R中重构data.frame:将物种-年份数据转为年份计数宽表

解决方法

嘿,这事儿用R来处理简直手到擒来!我给你准备了两种常用方法,不管你习惯用tidyverse工具包还是基础R语法都能轻松搞定~

方法一:用tidyverse(推荐,代码更直观易读)

首先我们先还原你的原始数据框,再一步步处理:

# 构造原始数据框
df <- data.frame(
  Scientific.Name = c("Sympetrum", "Celithemis eponina", "Celithemis elisa", 
                      "Celithemis elisa", "Cordulegaster maculata", 
                      "Calopteryx maculata", "Celithemis elisa", "Celithemis elisa"),
  Year = c(2012, 2012, 2012, 2012, 2011, 2011, 2013, 2013)
)

# 加载tidyverse包(如果没安装先运行install.packages("tidyverse"))
library(tidyverse)

# 统计次数并转成宽格式
result_df <- df %>%
  # 按物种和年份分组
  group_by(Scientific.Name, Year) %>%
  # 统计每组的出现次数
  summarise(Count = n(), .groups = "drop") %>%
  # 把年份转成列,缺失的年份填充0
  pivot_wider(names_from = Year, values_from = Count, values_fill = 0)

# 查看最终结果
print(result_df)

运行后得到的结果就是你想要的格式:

# A tibble: 5 × 4
  Scientific.Name        `2011` `2012` `2013`
  <chr>                   <int>  <int>  <int>
1 Calopteryx maculata         1      0      0
2 Celithemis elisa            0      2      2
3 Celithemis eponina          0      1      0
4 Cordulegaster maculata      1      0      0
5 Sympetrum                   0      1      0

方法二:用基础R语法(无需额外安装包)

如果不想加载第三方包,用基础R的table函数也能实现:

# 构造原始数据框(和上面一样)
df <- data.frame(
  Scientific.Name = c("Sympetrum", "Celithemis eponina", "Celithemis elisa", 
                      "Celithemis elisa", "Cordulegaster maculata", 
                      "Calopteryx maculata", "Celithemis elisa", "Celithemis elisa"),
  Year = c(2012, 2012, 2012, 2012, 2011, 2011, 2013, 2013)
)

# 生成交叉表,统计物种×年份的出现次数
species_year_table <- table(df$Scientific.Name, df$Year)

# 把交叉表转成数据框
result_df_base <- as.data.frame.matrix(species_year_table)

# 把行名(物种名)转成单独的列
result_df_base$Scientific.Name <- rownames(result_df_base)

# 调整列顺序,让物种名列在最前面
result_df_base <- result_df_base[, c("Scientific.Name", "2011", "2012", "2013")]

# 去掉行名,让格式更干净
rownames(result_df_base) <- NULL

# 查看结果
print(result_df_base)

运行后同样能得到你需要的格式:

Scientific.Name X2011 X2012 X2013
1      Calopteryx maculata     1     0     0
2           Celithemis elisa     0     2     2
3         Celithemis eponina     0     1     0
4 Cordulegaster maculata     1     0     0
5                Sympetrum     0     1     0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:35:44