如何在R中仅对数据框的指定两列执行pivot_wider操作?
解决方案:长格式转宽格式数据框转换
原始数据结构
用户的原始长格式分组数据框如下:
df = structure(list(Month = structure(c(946684800, 946684800, 946684800, 949363200, 949363200, 949363200, 951868800, 951868800, 951868800 ), tzone = "UTC", class = c("POSIXct", "POSIXt")), Country = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), levels = c("Italy", "Spain", "Portugal", "Ireland", "Germany", "France", "Belgium", "Netherlands", "Austria", "Finland"), class = "factor"), bucket = c("long", "medium", "short", "long", "medium", "short", "long", "medium", "short"), Share_bucket = c(0.403418993584752, 0.445804130974895, 0.150776875440353, 0.416193617674133, 0.458422829088678, 0.125383553237189, 0.613769196662502, 0.253456406949091, 0.132774396388407)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -9L), groups = structure(list( Month = structure(c(946684800, 949363200, 951868800), tzone = "UTC", class = c("POSIXct", "POSIXt")), Country = structure(c(1L, 1L, 1L), levels = c("Italy", "Spain", "Portugal", "Ireland", "Germany", "France", "Belgium", "Netherlands", "Austria", "Finland"), class = "factor"), .rows = structure(list(1:3, 4:6, 7:9), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame" ), row.names = c(NA, -3L), .drop = TRUE))
期望转换为如下宽格式:
Month Country short medium long 1 2000-01-01 00:00:00 Italy 0.151 0.446 0.403 2 2000-02-01 00:00:00 Italy 0.125 0.458 0.416 3 2000-03-01 00:00:00 Italy 0.133 0.253 0.614
实现代码
使用tidyr::pivot_wider结合dplyr工具即可完成转换,先取消数据框的分组状态(避免分组对转换的干扰),再调整列顺序匹配目标格式:
library(tidyr) library(dplyr) # 取消分组 df <- ungroup(df) # 长转宽并调整列顺序 df_wide <- df %>% pivot_wider( id_cols = c(Month, Country), # 作为行唯一标识的列 names_from = bucket, # 要转为列名的字段 values_from = Share_bucket # 对应列的值来源 ) %>% relocate(short, medium, long, .after = Country) # 调整列的显示顺序 # 查看结果(保留三位小数) print(df_wide, digits = 3)
关键参数说明
id_cols:指定Month和Country作为唯一行标识,确保每个时间-国家组合只保留一行names_from/values_from:完成长格式到宽格式的映射,将bucket的类别转为列名,对应值来自Share_bucketrelocate:调整列的显示位置,将short/medium/long列移至Country之后,匹配目标格式
内容的提问来源于stack exchange,提问作者Rollo99
相关产品推荐
相关产品推荐

