如何将数据框从行更改为列结构

How to change a data frame from rows to a column stucture

我在 R 中有以下数据框。

ID   | Year_Month | Amount
           
10001|2021-06     |  85
10001|2021-07     |  32.0
20032|2021-08     |  63
20032|2021-09     |  44.23
20033|2021-11     |  10.90

我想将此数据转换为如下所示:

ID   | 2021-06  | 2021-07 |2021-08 | 2021-09 | 2021-11
           
10001|    85    |   32    |   0    |    0    |   0
20032|     0    |   0     |   63   |  44.23  |   0
20033|     0    |   0     |   0    |   0     |  10.90

总计将显示在基于 Year_Month 列的列中。有人可以帮忙吗?我试过使用转置,但没有用。

你应该查看 tidyverse 包,它有一些非常好的数据整理功能。

## Loading the required libraries
library(dplyr)
library(tidyverse)

## Creating the dataframe
df = data.frame(ID=c(10001,10001,20032,20032,20033),
           Date=c('2021-06','2021-07','2021-08','2021-09','2021-11'),
           Amount = c(85,32,63,44.2,10.9))

## Pivot longer to wider
df_pivot = df %>%
  pivot_wider(names_from = Date, values_from = c(Amount)) 

## Replacing NA with 0
df_pivot[is.na(df_pivot)] = 0


df_pivot
# A tibble: 3 x 6
     ID `2021-06` `2021-07` `2021-08` `2021-09` `2021-11`
  <dbl>     <dbl>     <dbl>     <dbl>     <dbl>     <dbl>
1 10001        85        32         0       0         0  
2 20032         0         0        63      44.2       0  
3 20033         0         0         0       0        10.9