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

如何使用pivot_longer处理两组列并生成指定结构的数据集

Solution to Reshape Data with pivot_longer

Let's break down how to get your desired 4-column structure from the original wide dataframe. The key here is recognizing that your columns come in paired groups (y_1 ↔ flower_1, y_2 ↔ flower_2, etc.), so we can use regex patterns in pivot_longer to keep these pairs linked during reshaping.

Step 1: Load Required Library & Original Data

First, make sure you have the tidyverse loaded (since we're using tibble and pivot_longer):

library(tidyverse)

# Your original dataframe
first_df <- tibble(
  y_1 = seq(0, 1*3.14, length.out = 1000), 
  y_2 = seq(0, 2*3.14, length.out = 1000), 
  y_3 = seq(0, 3*3.14, length.out = 1000), 
  y_4 = seq(0, .2*3.14, length.out = 1000), 
  y_5 = seq(0, 1*3.14, length.out = 1000), 
  flower_1 = sin(y_1)-2.5, 
  flower_2 = cos(y_2), 
  flower_3 = sin(y_3)+2.5, 
  flower_4 = cos(y_4)+5, 
  flower_5 = sin(y_5)+7
)

Step 2: Reshape to Long Format

Use pivot_longer with a regex pattern to split column names into their component parts, then clean up the column names to match your desired output:

long_df <- first_df %>%
  # Split columns into value type (y/flower) and group number
  pivot_longer(
    cols = everything(),
    names_to = c(".value", "group"),
    names_pattern = "(y|flower)_(\\d)"
  ) %>%
  # Create the `flowers` and `y` columns with full original names
  mutate(
    flowers = str_c("flower_", group),
    y = str_c("y_", group)
  ) %>%
  # Reorder and rename columns to match your desired structure
  select(flowers, y, values_flowers = flower, values_y = y) %>%
  # Optional: Sort to group all entries for each flower together
  arrange(flowers, values_y)

Step 3: Verify the Output

If you run head(long_df), you'll see the structure matches your expected output:

head(long_df)
#> # A tibble: 6 × 4
#>   flowers   y     values_flowers values_y
#>   <chr>     <chr>          <dbl>    <dbl>
#> 1 flower_1  y_1           -2.5      0    
#> 2 flower_1  y_1           -2.50     0.00314
#> 3 flower_1  y_1           -2.49     0.00629
#> 4 flower_1  y_1           -2.49     0.00943
#> 5 flower_1  y_1           -2.48     0.0126
#> 6 flower_1  y_1           -2.47     0.0157

How It Works

  • The names_pattern = "(y|flower)_(\\d)" regex splits each column name into two groups: the first group (y or flower) becomes the name for the value columns, and the second group (1-5) is the group identifier.
  • Using .value in names_to tells pivot_longer to use the first regex group as column names for the values, keeping y and flower values paired by their group number.
  • We then add the full flowers and y column names, reorder everything, and sort to get the clean structure you wanted.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 23:17:35