如何在合并多个同格式DataFrame时转换数据形态?
Got it, let's work through this problem together. You have three DataFrames (price, size, performance) with the exact same structure, and you want to combine them while reshaping the data into a more flexible long format. Here's how to do it cleanly with the tidyverse, plus a base R alternative if you prefer.
Option 1: Using Tidyverse (Recommended for Readability)
First, make sure you have the tidyverse package installed and loaded—it combines dplyr for data manipulation and tidyr for reshaping:
# Install if you haven't already install.packages("tidyverse") library(tidyverse)
Step 1: Add a metric identifier to each DataFrame
We need a way to tell which rows came from which original DataFrame, so we'll add a metric column to each:
price <- price %>% mutate(metric = "price") size <- size %>% mutate(metric = "size") performance <- performance %>% mutate(metric = "performance")
Step 2: Combine all DataFrames
Use bind_rows() to stack them into a single DataFrame:
combined_df <- bind_rows(price, size, performance)
Step 3: Reshape to long format
Now we'll pivot the wide columns (A, B, C) into two columns: one for the category (like company name) and one for the corresponding value:
final_df <- combined_df %>% pivot_longer(cols = c(A, B, C), names_to = "company", # Name for the new category column values_to = "value") # Name for the new value column
Final Output Preview
If you print final_df, you'll get a structured long-format table like this:
# A tibble: 27 × 4 Year metric company value <dbl> <chr> <chr> <dbl> 1 2001 price A 1 2 2001 price B 2 3 2001 price C 4 4 2002 price A 2 5 2002 price B 3 6 2002 price C 5 7 2003 price A 3 8 2003 price B 4 9 2003 price C 6 10 2001 size A 1 # … with 17 more rows
Option 2: Using Base R
If you don't want to rely on external packages, you can achieve the same result with base R functions:
# Add metric column to each DataFrame price$metric <- "price" size$metric <- "size" performance$metric <- "performance" # Combine DataFrames combined_base <- rbind(price, size, performance) # Reshape to long format final_base <- reshape(combined_base, varying = c("A", "B", "C"), v.names = "value", timevar = "company", times = c("A", "B", "C"), direction = "long") # Clean up auto-generated row names row.names(final_base) <- NULL
This will produce a nearly identical structure to the tidyverse output, just with columns ordered slightly differently.
内容的提问来源于stack exchange,提问作者Weiwei Gu

