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

使用pivot_longer转换后列名反转,如何将x、y设为数据框列名?

问题解决:datasaurus_dozen_wide转长格式时列名反转的修复

问题场景

尝试将datasaurus_dozen_wide数据集转换为长格式,希望最终数据框以x、y作为列名,但转换后列名呈现反转状态,原代码及错误输出如下:

原代码

library(pacman)
p_load(tidyverse, purrr, datasauRus)
datasaurus_dozen_wide %>% 
  pivot_longer(everything(),
               names_to = c(".value", "set"),
               names_pattern = "(.*)_(.)")

错误输出

# A tibble: 284 × 14
    set    away bullseye circle  dino  dots h_lines high_…¹ slant…² slant…³  star
    <chr> <dbl>    <dbl>  <dbl> <dbl> <dbl>   <dbl>   <dbl>   <dbl>   <dbl> <dbl>
  1 x      32.3     51.2   56.0  55.4  51.1    53.4    57.6    52.9    47.7  58.2
  2 y      61.4     83.3   79.3  97.2  90.9    90.2    83.9    97.3    95.2  91.9
  3 x      53.4     59.0   50.0  51.5  50.5    52.8    51.3    59.0    44.6  58.2
  4 y      26.2     85.5   79.0  96.0  89.1    90.1    82.8    93.6    93.1  92.2
  5 x      63.9     51.9   51.3  46.2  50.2    47.1    50.8    56.4    43.9  58.7
  6 y      30.8     85.8   82.4  94.5  85.5    90.5    76.8    96.3    94.1  90.3
  7 x      70.3     48.2   51.2  42.8  50.1    42.4    37.0    37.8    41.6  57.3
  8 y      82.5     85.0   79.2  91.4  83.1    89.5    82.0    94.4    90.3  89.9
  9 x      34.1     41.7   44.4  40.8  50.6    42.7    42.9    39.9    49.2  58.1
 10 y      45.7     84.0   78.2  88.3  82.9    90.4    80.2    90.6    96.6  92.0
# … with 274 more rows, 3 more variables: v_lines <dbl>, wide_lines <dbl>,
#   x_shape <dbl>, and abbreviated variable names ¹​high_lines, ²​slant_down,
#   ³​slant_up

问题原因

datasaurus_dozen_wide的列名格式为[数据集名称]_[x/y](例如away_x、away_y),原代码存在两处错误:

  • names_to = c(".value", "set") 顺序颠倒,应该先提取数据集名称作为set,再提取x/y作为.value对应的列名
  • names_pattern = "(.*)_(.)" 匹配逻辑不精准,(.*)会过度匹配,且未限定只匹配x或y

修复代码

调整names_to的顺序,并修正names_pattern以精准匹配列名结构:

library(pacman)
p_load(tidyverse, purrr, datasauRus)
datasaurus_dozen_wide %>% 
  pivot_longer(everything(),
               names_to = c("set", ".value"),
               names_pattern = "(.*)_(x|y)")

正确输出示例

# A tibble: 1,846 × 3
   set       x     y
   <chr> <dbl> <dbl>
 1 away   32.3  61.4
 2 away   53.4  26.2
 3 away   63.9  30.8
 4 away   70.3  82.5
 5 away   34.1  45.7
 6 away   67.5  39.4
 7 away   43.7  65.3
 8 away   54.2  67.2
 9 away   61.1  57.4
10 away   46.1  57.5
# … with 1,836 more rows

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:45:32