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

如何使用pivot_longer()将多列转换为1个names_to列和2个values_to列

解决pivot_longer()多前缀列的重塑需求

原始数据框:

x <- tibble::tribble(
    ~kpu_operating, ~kpu_procedure, ~sf_operating, ~sf_procedure,
                3L,             2L,          572L,          120L,
                3L,             1L,          440L,          121L,
                6L,             NA,          535L,          122L,
                3L,             NA,          542L,          123L
)

需求:移除列名中的"kpu_"和"sf_"前缀,将"operating"和"procedure"存入新列unit;同时将kpu开头列的值放入n_unit,sf开头列的值放入sf_unit,得到目标数据框。

正确实现代码

library(tidyr)
library(dplyr)
library(stringr)

y <- x %>%
  pivot_longer(
    cols = everything(),
    names_to = c(".value", "unit"),
    names_pattern = "(kpu|sf)_(.*)"
  ) %>%
  rename(n_unit = kpu, sf_unit = sf) %>%
  mutate(unit = str_to_title(unit)) %>%
  relocate(unit, n_unit, sf_unit)

代码说明

  • names_pattern = "(kpu|sf)_(.*)":用正则表达式拆分列名,第一组匹配前缀kpu或sf,第二组匹配后面的operating/procedure
  • names_to = c(".value", "unit"):.value表示把第一组匹配到的前缀作为新列名,第二组存入unit列
  • rename():将自动生成的kpu和sf列重命名为需求中的n_unit和sf_unit
  • str_to_title():把unit列的字符串首字母大写,和目标格式一致
  • relocate():调整列顺序,和目标数据框对齐

之前写法的问题

  1. 两次pivot_longer()的写法:会生成unit和unit2两个列,且数据行数翻倍,无法将kpu和sf的对应值匹配到同一行,不符合需求。
  2. 单次pivot_longer()的错误写法:starts_with()仅支持单个前缀参数,names_prefix也不能传入向量,语法本身无效,无法正确拆分列名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:54:53