[英]How to count the frequency of unique factor across each row in r dataframe
[英]How to count frequency of a categorical variable (level) for each row in a dataframe
我想总结一下我的数据框中每个 ID 的每个级别(类别)的频率。 例如,如何分别为 ID 4003491503 生成值 1,2,0?
我试图tapply和计数,我不断收到错误。
RespondentID Case.A Case.B Case.C Freq Red Freq Blue Freq Missing/NA
1 4003491503 Red Blue Blue <b> 1 2 0 </b>
2 4003491653 Blue Red Red
3 4003491982 Red Blue Red
4 4003494862 Red Red NA
15 4003494880 Blue Blue Blue
我们可以将 'id.var' 作为 'RespondentID' 的数据集melt
,使用table
获取频率,将输出转换为data.frame
,更改列名并与原始数据集进行cbind
。
library(reshape2)
df2 <- as.data.frame.matrix(table(melt(df1, id.var='RespondentID')[-2], useNA='ifany'))
colnames(df2) <- paste0('Freq', colnames(df2))
cbind(df1, df2)
# RespondentID Case.A Case.B Case.C FreqBlue FreqRed FreqNA
#1 4003491503 Red Blue Blue 2 1 0
#2 4003491653 Blue Red Red 1 2 0
#3 4003491982 Red Blue Red 1 2 0
#4 4003494862 Red Red <NA> 0 2 1
#15 4003494880 Blue Blue Blue 3 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.