简体   繁体   English

获取具有不同类别的两个数据框的类别作为列的类别计数

[英]Get count of categories with the categories as column for two data frames having different categories

I have two data frames as below with some categories different.我有两个数据框,如下所示,有些类别不同。 For example, DF1 has A, B categories which DF2 doesn't have.例如,DF1 有 A、B 类别,而 DF2 没有。 I coded as below to get individual data frames y_t2, y_t3.我编码如下以获得单独的数据帧 y_t2,y_t3。

DF1 <- data.frame(Firm1 = c("A", "B", "C", "L", "M", "L"))
DF2 <- data.frame(Firm2 = c("L", "M", "N", "P")) 

library(dplyr)
y <- DF1 %>% group_by(Firm1) %>% 
  summarise(n = n())

y_t <- data.frame(t(y[,2:ncol(y)]))

colnames(y_t) <- data.frame(t(y[,1])) 

y_t2 <- y_t
y_t2$dataframe <- c("Firm1")


y <- DF2 %>% group_by(Firm2) %>% 
  summarise(n = n())

y_t <- data.frame(t(y[,2:ncol(y)]))

colnames(y_t) <- data.frame(t(y[,1])) 

y_t3 <- y_t
y_t3$dataframe <- c("Firm2")

I need to convert it into dummy variables for the categories of Group as below.我需要将其转换为 Group 类别的虚拟变量,如下所示。

最终输出

I checked links such as get the count and the price of category column then group by category but unable to progress using rbind.我检查了链接,例如获取类别列的计数和价格,然后按类别分组,但无法使用 rbind 进行。

Kindly advise how to code the logic to fetch the table.请建议如何编写逻辑代码以获取表格。 Thanks.谢谢。

t(table(do.call(rbind, lapply(list(DF1, DF2), stack))))

       values
ind     A B C L M N P
  Firm1 1 1 1 2 1 0 0
  Firm2 0 0 0 1 1 1 1

I found a little longer way, not as great as @onyambu's suggestion.我发现了一条更长的路,没有@onyambu 的建议那么好。

y_t4 <- rbind.fill(y_t2, y_t3)

y_t4[is.na(y_t4)] <- 0

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

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