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
- 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. - 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 likepercentGDP.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:
| year | percentGDP |
|---|---|
| 1980 | 17.8 |
| 1981 | 15.4 |
| 1982 | 16.5 |
| 1983 | 14.2 |
| 1984 | 10.3 |
| ... | ... |
内容的提问来源于stack exchange,提问作者Daniel Xavier
相关产品推荐
相关产品推荐

