重塑数据框列和行

问题描述

我有以下带有日期和五分位数的随机(缩短)数据集:

日期 五分位数
05/03/2021 5
05/03/2021 3
05/03/2021 1
04/03/2021 2
04/03/2021 4
03/03/2021 4
03/03/2021 1
03/03/2021 2

我想按如下方式重塑数据框:

日期 1 2 3 4 5
05/03/2021 1 0 1 0 1
04/03/2021 0 1 0 1 0
03/03/2021 1 1 0 0 1

新数据框将按日期聚合,新列中的各个五分位数。我已经探索了 dplyr 函数,但我不能完全正确:(

我将 Quintile 值设置为“as.character”,但我不确定我哪里出错了。

解决方法

您可以使用 pivot_wider 进行一些修改

编辑:为每个日期添加唯一标识符行,然后使用 pivot_wider

library(tidyverse)

# your data
df <- tribble(
  ~Date,~Quintile,"05/03/2021",5,3,1,"04/03/2021",2,4,"03/03/2021",2)

df1 <- df %>% 
  arrange(Quintile) %>% 
  group_by(Date,Quintile) %>% 
  mutate(row = row_number()) %>% # unique identifier
  mutate(count = n()) %>% 
  pivot_wider(names_from = Quintile,values_from = count) %>% 
  replace(is.na(.),0) %>% 
  select(-row) # remove unique identifier

enter image description here

,

这是我实际使用的数据集,以及实际发生错误的数据集(如对 TarJae 回答的评论中所述)。

enter image description here

编辑:

这是我在上面的数据帧上运行 TarJae 的代码(不包括唯一标识符)时的数据帧。没有产生警告错误,只是值似乎有问题。

enter image description here

使用唯一标识符,结果是:

enter image description here

,

这是一个使用 table

的简单基本 R 选项
> table(df)
            Quintile
Date         1 2 3 4 5
  03/03/2021 1 1 0 1 0
  04/03/2021 0 1 0 1 0
  05/03/2021 1 0 1 0 1

reshape

reshape(
  data.frame(table(df)),direction = "wide",idvar = "Date",timevar = "Quintile")

给予

        Date Freq.1 Freq.2 Freq.3 Freq.4 Freq.5
1 03/03/2021      1      1      0      1      0
2 04/03/2021      0      1      0      1      0
3 05/03/2021      1      0      1      0      1

aggregate

aggregate(
  Quintile ~ Date,df,function(x) table(factor(x,levels = sort(unique(df$Quintile)))))

给予

        Date Quintile.1 Quintile.2 Quintile.3 Quintile.4 Quintile.5
1 03/03/2021          1          1          0          1          0
2 04/03/2021          0          1          0          1          0
3 05/03/2021          1          0          1          0          1