如何计算R中2行的值频率 [英] how to Count the values frequency of 2 rows in R

查看:29
本文介绍了如何计算R中2行的值频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张这样的桌子:

Menu name | Transcode
Menu 1    | a1
Menu 2    | a2
Menu 3    | a3
Menu 1    | a1
Menu 3    | a2
Menu 1    | a1
Menu 1    | a3

如何在R.中实现这一枢纽,以计算与x列相关的x列(菜单名称)中的值频率和y列(Trancode)的频率

How can I achieve this pivot in R. to count the number of values frequency in column x (menu name) and the frequency of column y (Trancode) in relation with column x

推荐答案

将输出分成两列而不是两列可能更好(以便于后处理).我们使用table获得频率计数,使用addmarginssum递增每个"Menu_name"的计数,转换为"data.frame".如有必要,我们可以在第一列之前order输出("res").

Instead of a two column output, it may be better to have it in three columns (for easier post-processing). We get the frequency counts using table, use addmargins to sum up the counts for each "Menu_name", convert to 'data.frame'. If needed, we can order the output ('res') by the first column.

 res <- as.data.frame(addmargins(table(df1), 2))
 res1 <- res[order(res[,1]),]
 row.names(res1) <- NULL
 res1[1:2] <- lapply(res1[1:2], as.character)

然后,使用rbind创建总和"行

Then, use rbind to create the "Grand Sum" row

rbind(res1, list("Menu", "Grand Sum", sum(res1$Freq)))
#    Menu_name Transcode Freq
#1     Menu 1        a1    3
#2     Menu 1        a2    0
#3     Menu 1        a3    1
#4     Menu 1       Sum    4
#5     Menu 2        a1    0
#6     Menu 2        a2    1
#7     Menu 2        a3    0
#8     Menu 2       Sum    1
#9     Menu 3        a1    0
#10    Menu 3        a2    1
#11    Menu 3        a3    1
#12    Menu 3       Sum    2
#13      Menu Grand Sum   14

这篇关于如何计算R中2行的值频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆