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

R语言:如何将DataFrame的一行复制到另一DataFrame并转为列?

Fixing Your Data Frame Conversion Issue

Let's break down what went wrong and how to get your desired df2 format correctly.

Why Your Original Code Failed

  1. Incorrect Year Sequence: c("1980":"1990") doesn't work because the colon operator (:) isn't designed for string values. It will either throw an error or generate an invalid sequence instead of the years you want.
  2. Mishandling the Row Extraction: c(df1[1,1:11]) treats the selected row (a data frame subset) as multiple column vectors, which is why you ended up with columns like percentGDP.X1980. Pairing this with a repeated year sequence caused duplicate values across rows.

Solution 1: Base R Approach

Since your df1 is in wide format (years as columns), we'll extract values and corresponding years properly:

# Extract numeric values from the first row (exclude the "Country" column)
savings_values <- as.numeric(df1[1, -1])

# Extract year labels by removing the "X" prefix from column names
year_labels <- sub("^X", "", names(df1)[-1])

# Build the desired data frame
df2 <- data.frame(
  year = year_labels,
  percentGDP = savings_values
)

Solution 2: Tidyverse (dplyr + tidyr) Approach

If you prefer a more readable, pipe-based workflow, use pivot_longer to reshape the data directly:

library(tidyverse)

# Slice the first row, reshape to long format, clean year labels
df2 <- df1 %>%
  slice(1) %>%  # Keep only the first row (Brazil)
  pivot_longer(
    cols = starts_with("X"),  # Target all year columns starting with "X"
    names_to = "year",        # Name the new year column
    values_to = "percentGDP"  # Name the new value column
  ) %>%
  mutate(year = str_remove(year, "X")) %>%  # Remove "X" from year strings
  select(year, percentGDP)  # Keep only the two columns we need

What You'll Get

Both methods will produce your desired df2 structure:

yearpercentGDP
198017.8
198115.4
198216.5
198314.2
198410.3
......

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:47:30