简体   繁体   中英

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

I have an R dataframe that looks like this:

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

And I want to convert into a dataframe like this with counts for each code per ID (key):

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

The easiest approach is table and coerce it to 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


Or use pivot_wider from tidyr

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

-ouptut

# 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

data

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM