Getting R Frequency counts for all possible answers

会有一股神秘感。 提交于 2019-12-04 04:33:07

问题


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')

I get a result of

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

I'm looking for a result of

    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?


回答1:


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

Edit: 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



回答2:


This kind of tasks is easily done with package dplyr. For keeping the non-used values of R, you have to define R as factor and use tidyr's complete-function

library(dplyr)
library(tidyr)
df %>%
    mutate(R = factor(R, levels=1:10)) %>%
    group_by(R) %>%
    summarise(freq=n()) %>%
    complete(R, fill=list(freq=0))


来源:https://stackoverflow.com/questions/36784621/getting-r-frequency-counts-for-all-possible-answers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!