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

如何在R语言中转置并转换DataFrame的指定部分数据?

Reshape Your R DataFrame Efficiently (For Beginners)

Hey there! Since you're just starting out with R, I'll show you a straightforward, efficient way to reshape your DataFrame using the tidyverse package—it's designed to make data manipulation feel intuitive, even for new folks.

First, let's recap your original data: you've got a wide-format DataFrame with countries, indicators, and year-specific values. To "transpose and convert" it into a more usable structure, we'll use two key functions from the tidyr part of tidyverse: pivot_longer and pivot_wider.

Step 1: Set Up the Package

If you haven't installed tidyverse yet, run this first:

install.packages("tidyverse")
library(tidyverse)

Step 2: Reshape the Data

Here's the full code to get your desired format (I'll break it down line by line below):

# Your original DataFrame
df <- data.frame(
  Country = c("USA","USA","USA","USA","India","India","India","India","China","China","China","China"),
  Indicator = rep(c("Population","GDP","Debt","Currency"), times=3),
  `2011` = rep(c(1,2,3,4), each=3),
  `2012` = rep(c(4,5,6,7), each=3),
  `2013` = rep(c(8,9,11,12), each=3)
)

# Reshape to transposed, clean format
reshaped_df <- df %>%
  # Convert wide year columns into long format (Year + Value columns)
  pivot_longer(cols = starts_with("20"), names_to = "Year", values_to = "Value") %>%
  # Combine Country and Indicator into a single descriptive column name
  unite(col = "Country_Indicator", Country, Indicator, sep = "_") %>%
  # Pivot back to wide format with Year as rows, and Country-Indicator pairs as columns
  pivot_wider(names_from = Country_Indicator, values_from = Value)

# Check the result
print(reshaped_df)

What Each Step Does:

  • pivot_longer: Takes your separate year columns (2011, 2012, 2013) and turns them into two columns: Year (storing the year string) and Value (storing the corresponding number). This simplifies the data for further reshaping.
  • unite: Merges the Country and Indicator columns into one (e.g., USA_Population), so each unique combination gets its own column later.
  • pivot_wider: Converts the long data back to a wide format, but now with years as rows and country-indicator pairs as columns—this is the transposed, organized structure you're looking for.

Alternative Format (If You Prefer)

If you wanted indicators as rows instead of years, just tweak the code slightly to combine Country and Year instead:

reshaped_df_alt <- df %>%
  pivot_longer(cols = starts_with("20"), names_to = "Year", values_to = "Value") %>%
  unite(col = "Country_Year", Country, Year, sep = "_") %>%
  pivot_wider(names_from = Country_Year, values_from = Value)

print(reshaped_df_alt)

This approach is far more readable than base R's reshape() function, which can be tricky for beginners. The tidyverse syntax is designed to be human-friendly, so you can easily adjust it if your desired format changes later.

内容的提问来源于stack exchange,提问作者maplesyrup123

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 16:56:14