在R语言中将分组行元素转为列名、对应值转为列数据的快速实现方法
Hey there! Reshaping your long-format dataframe into the wide one you need doesn't have to be complicated. Let's walk through two simple, efficient methods to get exactly what you're looking for.
Method 1: Using tidyverse (Recommended for Readability)
The pivot_wider() function from the tidyverse package is built for this kind of reshaping. We just need a quick row identifier to keep track of which value belongs to which position in each group:
library(tidyverse) # Add a row number within each group to map values correctly dataframe_1 <- dataframe_1 %>% group_by(a) %>% mutate(row_num = row_number()) %>% ungroup() # Reshape to wide format dataframe_2 <- dataframe_1 %>% pivot_wider(names_from = a, values_from = b) %>% select(-row_num) # Remove the temporary identifier
This will produce a dataframe that matches your dataframe_2 perfectly—each group (A, B, C) becomes a column, with their corresponding values aligned in rows 1 and 2.
Method 2: Base R (No External Packages Needed)
If you prefer not to load additional packages, a concise base R solution works great here (since each group has exactly 2 values):
# Split 'b' values by groups in 'a', then bind as columns dataframe_2 <- do.call(cbind.data.frame, split(dataframe_1$b, dataframe_1$a))
This one-liner splits the b column into a list of vectors (one per group in a), then converts that list into a dataframe with group names as column headers. It's fast and gets the job done with minimal code.
Either method will give you this desired output:
A B C 1 1 12 4 2 2 2 5
内容的提问来源于stack exchange,提问作者Earl Mascetti

