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

在R中按组织与月份透视数据框:将值转为列名并拼接关联列名

解决方案:R数据框透视拼接处理

步骤1:加载依赖并构造示例数据

首先加载tidyverse包(整合了dplyr、tidyr、stringr等工具),并构造你提供的示例数据框:

library(tidyverse)

df <- tibble(
  organization = c("A", "A", "B", "B", "C", "D"),
  month = c('jan','feb','jan','feb','feb','feb'),
  therapyA = c(NA,'in person',NA,'telehealth',NA,'in person'),
  therapyB = c('in person','in person',NA,'telehealth',NA,'in person'),
  therapyC = c(NA,'in person','telehealth','telehealth',NA,'in person'),
  therapyD = c(NA,'in person',NA,'telehealth','telehealth','in person')
)

步骤2:数据透视与拼接处理

通过以下代码实现需求:

result <- df %>%
  # 将therapy系列列转成长格式,同时过滤NA值
  pivot_longer(
    cols = starts_with("therapy"),
    names_to = "therapy_type",
    values_to = "service_mode",
    values_drop_na = TRUE
  ) %>%
  # 修正治疗类型名称的大小写(匹配输出格式)
  mutate(therapy_type = str_to_title(therapy_type)) %>%
  # 按分组维度聚合,拼接同服务模式下的治疗类型
  group_by(organization, month, service_mode) %>%
  summarise(therapy_list = str_c(therapy_type, collapse = ","), .groups = "drop") %>%
  # 转回宽格式,将服务模式作为新列名
  pivot_wider(
    names_from = service_mode,
    values_from = therapy_list,
    values_fill = NA
  ) %>%
  # 调整新列名的格式为标题式大写
  rename_with(str_to_title, starts_with(c("in", "tele")))

最终结果

运行代码后得到的结果与你需求一致:

print(result)

输出:

# A tibble: 6 × 4
  organization month `In Person`                          `Telehealth`                        
  <chr>        <chr> <chr>                               <chr>                               
1 A            jan   TherapyB                            NA                                  
2 A            feb   TherapyA,TherapyB,TherapyC,TherapyD NA                                  
3 B            jan   NA                                  TherapyC                            
4 B            feb   NA                                  TherapyA,TherapyB,TherapyC,TherapyD
5 C            feb   NA                                  TherapyD                            
6 D            feb   TherapyA,TherapyB,TherapyC,TherapyD NA                                  

代码说明

  • pivot_longer:把宽表转为长表,聚焦治疗类型和对应的服务模式,同时过滤NA值减少无效数据。
  • str_to_title:将therapyA转换为TherapyA,匹配你需要的输出格式。
  • group_by + summarise:按组织、月份、服务模式分组,用逗号拼接同组的治疗类型名称。
  • pivot_wider:将服务模式(in person/telehealth)转为新列名,填充对应的拼接结果,缺失值用NA补充。
  • rename_with:将新列名调整为标题式大写,让输出更规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:18:18