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

如何用pivot_longer()转换多列R数据?现有代码无法生成目标结果

R语言:将宽格式数据框转换为指定长格式

原始数据框

df <- data.frame(year = c("2001", "2001", "2001", "2002", "2002", "2002", 
                          "2003", "2003", "2003", "2004", "2004", "2004"), 
             city = c("Rome", "Rome", "Rome", "London", "London", "London", 
                      "New York", "New York", "New York", "Paris", "Paris", "Paris"),
             position_1 = c("first", "first", "first", "second", "second", "second", 
                            "third", "third", "third", "fourth", "fourth", "fourth"),
             position_2 = c("fifth", "fifth", "fifth", "sixth", "sixth", "sixth", 
                            "seventh", "seventh", "seventh", "eighth", "eighth", "eighth"), 
             position_3 = c("ninth", "ninth", "ninth", "eleventh", "eleventh", "eleventh", 
                            "twelfth", "twelfth", "twelfth", "thirteenth", "thirteenth", "thirteenth"))

需求

将上述宽格式数据转换为包含year、city、new_position(对应原position_1/2/3列名)及对应位置值的长格式表格。

问题代码

尝试了以下代码但未得到预期结果:

df <- df %>% 
  pivot_longer(cols = position_1:position_3,
               names_to = "new_position")

正确实现方法

问题出在缺少values_to参数,该参数用于指定存储原位置列值的新列名。此外原数据存在重复行,可按需去重:

1. 保留所有原始行的转换

library(tidyr)
library(dplyr)

df_long <- df %>%
  pivot_longer(
    cols = position_1:position_3, # 选择需要转换的列
    names_to = "new_position",    # 原列名存入该列
    values_to = "position_value"  # 原列的值存入该列
  )

2. 去除冗余重复行后的转换

原数据中每个year+city组合有3条完全重复的行,转换后会产生冗余,先用distinct()去重再转换:

df_long_unique <- df %>%
  distinct() %>% # 去除完全重复的行
  pivot_longer(
    cols = position_1:position_3,
    names_to = "new_position",
    values_to = "position_value"
  )

结果说明

转换后的长格式表格结构示例(以去重后的结果为例):

yearcitynew_positionposition_value
2001Romeposition_1first
2001Romeposition_2fifth
2001Romeposition_3ninth
2002Londonposition_1second
............

内容的提问来源于stack exchange,提问作者always.learning

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 00:21:29