获取所有可能答案的R频率计数 [英] Getting R Frequency counts for all possible answers

查看:70
本文介绍了获取所有可能答案的R频率计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从R开始,但仍在语法上找到自己的出路. 我希望获得比例变量的频率,该变量的值为0到10和NA.

I've started with R and I'm still finding my way with syntax. I'm looking to get the frequencies for a scaled variable which has values of 0 through 10 and NA.

Id <- c(1,2,3,4,5)
ClassA <- c(1,NA,3,1,1)
ClassB <- c(2,1,1,3,3)
R <- c(5,5,7,NA,9)
S <- c(3,7,NA,9,5)
df <- data.frame(Id,ClassA,ClassB,R,S)
library(plyr)
count(df,'R')

我得到的结果

     R freq
  1  5    2
  2  7    1
  3  9    1
  4 NA    1

我正在寻找

    R freq
1   0    0
2   1    0
3   2    0
4   3    0
5   4    0
6   5    2
7   6    0
8   7    1
9   8    0
10  9    1
11  10   0
12  NA   1

如果我有向量显示可能的结果

If I have the vector showing the possible results

RAnswers <- c(0,1,2,3,4,5,6,7,8,9,10,NA)

我如何将其与数据集一起应用以获得上述结果?

How would I apply it with the data set to get the above result?

推荐答案

这是围绕table()match()replace()构建的基本R解决方案:

Here's a base R solution built around table(), match(), and replace():

freq <- table(df$R,useNA='ifany');
freq;
##
##    5    7    9 <NA>
##    2    1    1    1
R <- c(0:10,NA);
df2 <- data.frame(R=R,freq=freq[match(R,as.integer(names(freq)))]);
df2$freq[is.na(df2$freq)] <- 0;
df2;
##     R freq
## 1   0    0
## 2   1    0
## 3   2    0
## 4   3    0
## 5   4    0
## 6   5    2
## 7   6    0
## 8   7    1
## 9   8    0
## 10  9    1
## 11 10    0
## 12 NA    1


弗兰克有一个更好的答案,这是如何在因子上使用table()来获得所需输出的方法:


Frank has a better answer, here's how you can use table() on a factor to get the required output:

setNames(nm=c('R','freq'),data.frame(table(factor(df$R,levels=RAnswers,exclude=NULL))));
##       R freq
## 1     0    0
## 2     1    0
## 3     2    0
## 4     3    0
## 5     4    0
## 6     5    2
## 7     6    0
## 8     7    1
## 9     8    0
## 10    9    1
## 11   10    0
## 12 <NA>    1

这篇关于获取所有可能答案的R频率计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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