簡體   English   中英

創建一個包含另一個數據框列中唯一值計數的 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_widertidyr

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM