如何重塑DataFrame:合并年份列并填充缺失值为NA
解决多区域温度数据的重塑问题
核心思路是拆分列名中的区域与属性信息,通过「宽表转长→整理年份映射→长表转宽」的流程实现需求,以下是可直接复用的代码方案:
1. 模拟数据集(匹配你的结构)
先模拟和你类似的多区域数据结构,方便你对照调整:
library(tidyverse) # 模拟示例数据:包含Antarctica、Arctic两个区域的年份及温度数据 df <- tibble( Antarctica.Year.CE = c(2000, 2001, 2002), Antarctica.Temp = c(-50.1, -49.8, -51.2), Antarctica.Min = c(-62.3, -61.5, -63.1), Antarctica.Max = c(-38.2, -37.9, -39.0), Arctic.Year.CE = c(2001, 2002, 2003), Arctic.Temp = c(-12.5, -11.8, -13.0), Arctic.Min = c(-25.1, -24.3, -26.2), Arctic.Max = c(-0.2, 0.5, -1.1) )
2. 数据重塑步骤
# 第一步:将所有列转长格式,同时拆分列名为「区域」和「属性」 df_long <- df %>% pivot_longer( cols = everything(), names_to = c("Region", "Attribute"), names_sep = "\\.", # 按列名中的点分隔符拆分,若你的分隔符不同可修改 values_to = "Value" ) # 第二步:提取年份数据,建立区域-年份的映射关系 year_mapping <- df_long %>% filter(Attribute == "Year.CE") %>% # 匹配你的年份列命名 rename(Year = Value) %>% select(Region, Year) # 第三步:提取温度相关属性数据 temp_data <- df_long %>% filter(Attribute != "Year.CE") %>% select(Region, Attribute, Value) # 第四步:合并并转宽,生成目标格式(自动填充NA) final_df <- year_mapping %>% full_join(temp_data, by = "Region") %>% pivot_wider( names_from = c(Region, Attribute), values_from = Value ) %>% arrange(Year)
3. 关键调整说明
- 如果你的列名分隔符不是
.,修改names_sep参数(比如下划线就用"_") - 如果年份列的命名不是
Year.CE,调整filter(Attribute == "Year.CE")中的匹配值 full_join会自动生成所有区域-年份的组合,缺失数据的位置自动填充NA
内容的提问来源于stack exchange,提问作者Sophie Williams
相关产品推荐
相关产品推荐

