Getting R Frequency counts for all possible answers

后端 未结 2 801
忘了有多久
忘了有多久 2021-01-20 19:08

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.

         


        
2条回答
  •  后悔当初
    2021-01-20 19:34

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

    freq <- table(df$R,useNA='ifany');
    freq;
    ##
    ##    5    7    9 
    ##    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     1
    

提交回复
热议问题