本文介绍了R中的5个排名的频率计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在问卷中有5个项目A, B, C, D, E,并让受访者对它们进行排名.数据看起来像这样,

Say I have 5 items A, B, C, D, E in a questionnaire and got respondents to rank them. The data looks like this,

> df
  rank1 rank2 rank3 rank4 rank5
1     A     B     C     D     E
2     A     C     B     D     E
3     C     A     B     E     D
4     B     A     C     D     E
5     A     B     D     C     E

我如何按项目计算每个排名的频率,以便输出看起来像这样,

How do I count the frequency of each rank by item so the output looks like this,

  item rank1 rank2 rank3 rank4 rank5
1    A     3     2     0     0     0
2    B     1     2     2     0     0
3    C     1     1     2     1     0
4    D     0     0     1     3     1
5    E     0     0     0     1     4

推荐答案

在使用base R

lvls <- sort(unique(unlist(df)))
sapply(df, function(x) table(factor(x, levels =lvls)))
#   rank1 rank2 rank3 rank4 rank5
#A     3     2     0     0     0
#B     1     2     2     0     0
#C     1     1     2     1     0
#D     0     0     1     3     1
#E     0     0     0     1     4

或仅调用一次table

table(unlist(df), c(col(df)))
#    1 2 3 4 5
#  A 3 2 0 0 0
#  B 1 2 2 0 0
#  C 1 1 2 1 0
#  D 0 0 1 3 1
#  E 0 0 0 1 4


或与qdapTools

library(qdapTools)
t(mtabulate(df))

数据

df <- structure(list(rank1 = c("A", "A", "C", "B", "A"), rank2 = c("B",
"C", "A", "A", "B"), rank3 = c("C", "B", "B", "C", "D"), rank4 = c("D",
"D", "E", "D", "C"), rank5 = c("E", "E", "D", "E", "E")), .Names = c("rank1",
 "rank2", "rank3", "rank4", "rank5"), class = "data.frame", row.names = c("1",
 "2", "3", "4", "5"))

这篇关于R中的5个排名的频率计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:44