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

基于重复数据构建Spread数据的技术方案咨询(类tidyr::spread但有差异)

Solution for Spreading Data with Accumulated Columns for Duplicates

Here's a step-by-step approach using R's dplyr and tidyr packages to achieve your desired output—this builds on the logic of spread but adds the ability to handle multiple associated columns (X1 and X3) for each duplicate X2 value:

Step 1: Add a Sequence Identifier to Each X2 Group

First, we need to track which occurrence each row is for its X2 value. This lets us map each duplicate row to a unique "step" in the wide format.

library(dplyr)
library(tidyr)

# Sample input data (matching your example)
input_df <- data.frame(
  X1 = c("1", "2", "3", "4", "F", "D", "E"),
  X2 = c(1, 2, 3, 4, 5, 1, 5),
  X3 = c(10, 11, 13, 12, 16, 17, 18),
  stringsAsFactors = FALSE
)

# Add sequence number per X2 group
df_with_seq <- input_df %>%
  group_by(X2) %>%
  mutate(seq = row_number()) %>%  # Assigns 1, 2, ... for each duplicate X2
  ungroup()

Step 2: Reshape to Wide Format with Pivot_Wider

Unlike the older spread function, pivot_wider can handle multiple value columns at once. We'll use it to create separate columns for X1 and X3 for each sequence number.

df_wide <- df_with_seq %>%
  pivot_wider(
    id_cols = X2,  # Keep X2 as the identifier column
    names_from = seq,  # Use the sequence number to name new columns
    values_from = c(X1, X3),  # Spread both X1 and X3 columns
    names_sep = "."  # Separate column name parts with a dot (e.g., X1.1)
  )

Step 3: Reorder Columns to Pair X1 and X3 for Each Step

By default, pivot_wider will group all X1 columns first, then all X3 columns. We'll reorder them to pair X1 and X3 for each sequence (e.g., X1.1 followed by X3.1, then X1.2 followed by X3.2).

# Get unique sequence numbers to define column order
seqs <- unique(df_with_seq$seq)
col_order <- c("X2", unlist(lapply(seqs, function(k) c(paste0("X1.", k), paste0("X3.", k)))))

# Apply the column order
final_df <- df_wide %>%
  select(all_of(col_order))

Final Output

Running this code will produce exactly the format you need:

# A tibble: 5 × 7
    X2 X1.1 X3.1 X1.2 X3.2 X1.3 X3.3
  <dbl> <chr> <dbl> <chr> <dbl> <chr> <dbl>
1     1 1        10 D        17 NA       NA
2     2 2        11 NA       NA NA       NA
3     3 3        13 NA       NA NA       NA
4     4 4        12 NA       NA NA       NA
5     5 F        16 E        18 NA       NA

This approach automatically handles any number of duplicates (up to 102 or more) and preserves the association between X1 and X3 for each occurrence of X2.

内容的提问来源于stack exchange,提问作者Sang won kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:56:25