使用R语言将多行转单列:DataFrame-1转换为目标DataFrame-2
Hey there! Let's sort out this DataFrame reshaping task in R. Since you need to convert DataFrame-1 to your target DataFrame-2 (turning multi-row data into a single column), I’ll walk you through two common scenarios and the simplest ways to pull this off using both tidyverse tools and base R.
Scenario 1: Convert wide-format columns into a single long column
This is the classic "wide to long" reshaping—say you have multiple columns of data, and you want all their rows stacked into one single column.
Example DataFrame-1 (wide format):
df1 <- data.frame( Category = c("Group A", "Group B", "Group C"), Metric1 = c(10, 20, 30), Metric2 = c(15, 25, 35), Metric3 = c(12, 22, 32) )
Target DataFrame-2 (single column):
df2 <- data.frame( AllValues = c(10, 15, 12, 20, 25, 22, 30, 35, 32) )
How to do it:
Using tidyr::pivot_longer() (tidyverse, most flexible):
library(tidyr) # If you don't need to keep the Category column: df2 <- df1 %>% pivot_longer( cols = everything(), # Grab all columns names_to = NULL, # We don't care about original column names values_to = "AllValues" # Name for our new single column ) # If you want to keep the Category and sort by it first: df2 <- df1 %>% pivot_longer( cols = starts_with("Metric"), # Only select the Metric columns names_to = NULL, values_to = "AllValues" ) %>% arrange(Category)
Using base R stack() (quick for simple cases):
# Works if all columns are the same data type df2 <- data.frame(AllValues = stack(df1)$values)
Scenario 2: Combine multiple rows per group into a single cell in one column
If your goal is to aggregate rows from the same group into a single string entry in a column (e.g., merging all values for a single ID into one cell), here's how:
Example DataFrame-1 (grouped rows):
df1 <- data.frame( ID = c(1, 1, 1, 2, 2), Item = c("Apple", "Banana", "Cherry", "Date", "Elderberry") )
Target DataFrame-2 (aggregated single column):
df2 <- data.frame( ID = c(1, 2), CombinedItems = c("Apple, Banana, Cherry", "Date, Elderberry") )
How to do it:
Using dplyr + tidyr (tidyverse):
library(dplyr) df2 <- df1 %>% group_by(ID) %>% summarise( CombinedItems = paste(Item, collapse = ", ") # Use any delimiter you want ) %>% ungroup()
Using base R aggregate():
df2 <- aggregate(Item ~ ID, data = df1, FUN = function(x) paste(x, collapse = ", "))
Just adjust the column names (like Metric, ID, Item) to match your actual DataFrame-1 structure, and you’ll get exactly the DataFrame-2 you need.
内容的提问来源于stack exchange,提问作者userRC

