创建一个包含另一个数据框列中唯一值计数的 R 数据框

Create an R dataframe containing the counts of unique values in another dataframe column

我有一个如下所示的 R 数据框:

ID number   Code
D001        F11
D001        F12
F002        D13
F002        F11
E003        C12

我想转换成这样的数据框,每个 ID(键)的每个代码都有计数:

ID number   F11  F12  D13  C12
D001         1    1    0    0
F002         1    0    1    0
E003         0    0    0    1   

最简单的方法是 table 并将其强制为 data.frame

as.data.frame.matrix(table(df1))
      C12 D13 F11 F12
D001   0   0   1   1
E003   1   0   0   0
F002   0   1   1   0


或使用 pivot_wider 来自 tidyr

library(tidyr)
library(dplyr)
df1 %>%
    pivot_wider(names_from = Code, values_from = Code,
       values_fn = length, values_fill = 0)

-输出

# A tibble: 3 x 5
  IDnumber   F11   F12   D13   C12
  <chr>    <int> <int> <int> <int>
1 D001         1     1     0     0
2 F002         1     0     1     0
3 E003         0     0     0     1

数据

df1 <- structure(list(IDnumber = c("D001", "D001", "F002", "F002", "E003"
), Code = c("F11", "F12", "D13", "F11", "C12")), class = "data.frame", row.names = c(NA, 
-5L))