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

在R语言中将分组行元素转为列名、对应值转为列数据的快速实现方法

Efficiently Reshape dataframe_1 to dataframe_2 in 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.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 06:59:07