简体   繁体   English

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

[英]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_widertidyr

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 创建一个 dataframe 的列,该列将包含一个列的唯一值和另一个 dataframe 的唯一列名 - Create a dataframe with a column that will include unique values of a column and unique column names of another dataframe R循环遍历数据框列中的唯一值以根据条件创建另一个 - R Loop over unique values in a dataframe column to create another one based on conditions R 如何从 dataframe 创建包含多组计数的表? - R how to create table from dataframe containing counts over groups? 对R中数据框的一列进行计数 - Doing counts for a column of a dataframe in R 要在 R 中列出的数据框列的唯一值 - Unique values of a dataframe column to list in R 子集 dataframe 通过 R 中的列中的唯一值 - Subset dataframe by unique values within a column in R R Dataframe 中列组合的唯一列值 - Unique column values on a combination of columns in R Dataframe 数据帧R中值组合的计数 - counts of combinations of values in a dataframe R 如何基于一个数据框中的列的值和R中另一个数据框的列标题名称有条件地创建新列 - how to conditionally create new column based on the values of a column in one dataframe and the column header names of another dataframe in R 在一个 dataframe 中创建一个列,基于另一个 dataframe 在 R 中的另一列 - Create a column in one dataframe based on another column in another dataframe in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM