[英]Create an R dataframe containing the counts of unique values in another dataframe column
I have an R dataframe that looks like this:我有一个 R 数据框,如下所示:
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(键)的每个代码都有计数:
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
最简单的方法是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
Or use pivot_wider
from tidyr
或者使用pivot_wider
的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
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.