如何用pivot_longer对多组成对列的宽数据集进行转长处理?
R宽格式转长格式:成对列转换方案
原始宽格式数据
代码定义:
df <- data.frame( Pseudonym = c("aa", "bb"), KE_date_1 = c("2022-04-01", "2022-04-03"), KE_content_2 = c("high pot", "high pot"), KE_date_3 = c("2022-08-01", "2022-08-04"), KE_content_4 = c("high pot return", "high pot return") )
对应表格:
| Pseudonym | KE_date_1 | KE_content_2 | KE_date_3 | KE_content_4 |
|---|---|---|---|---|
| aa | 2022-04-01 | high pot | 2022-08-01 | high pot return |
| bb | 2022-04-03 | high pot | 2022-08-04 | high pot return |
目标长格式数据
代码定义:
df2 <- data.frame( Pseudonym = c("aa", "aa", "bb", "bb"), KE_date = c("2022-04-01", "2022-08-01", "2022-04-03", "2022-08-04"), KE_content = c("high pot", "high pot return", "high pot", "high pot return") )
对应表格:
| Pseudonym | KE_date | KE_content |
|---|---|---|
| aa | 2022-04-01 | high pot |
| aa | 2022-08-01 | high pot return |
| bb | 2022-04-03 | high pot |
| bb | 2022-08-04 | high pot return |
解决方案
方法一:使用tidyverse工具(推荐)
利用purrr的map2函数匹配成对的日期和内容列,再合并结果:
library(tidyverse) # 提取所有日期列和内容列 date_cols <- df %>% select(starts_with("KE_date")) content_cols <- df %>% select(starts_with("KE_content")) # 按组转换并合并 df_long <- bind_rows( map2(date_cols, content_cols, ~ tibble(KE_date = .x, KE_content = .y)) ) %>% bind_cols(Pseudonym = rep(df$Pseudonym, ncol(date_cols))) %>% select(Pseudonym, KE_date, KE_content)
方法二:Base R原生实现
无需加载外部包,通过循环遍历成对列实现转换:
# 获取日期列和内容列的索引 date_idx <- grep("KE_date", names(df)) content_idx <- grep("KE_content", names(df)) # 初始化结果数据框 df_long <- data.frame(Pseudonym = character(), KE_date = character(), KE_content = character()) # 遍历每一组列并拼接 for (i in seq_along(date_idx)) { temp_df <- data.frame( Pseudonym = df$Pseudonym, KE_date = df[[date_idx[i]]], KE_content = df[[content_idx[i]]] ) df_long <- rbind(df_long, temp_df) } # 重置行名 rownames(df_long) <- NULL
内容的提问来源于stack exchange,提问作者Raidho
相关产品推荐
相关产品推荐

