Table by row with R

前端 未结 4 1471
暗喜
暗喜 2021-01-22 04:19

I would like to tabulate by row within a data frame. I can obtain adequate results using table within apply in the following example:

         


        
相关标签:
4条回答
  • 2021-01-22 04:44

    Here's a table solution:

    table(
        rep(rownames(df.1),5),
        unlist(df.1[,4:8]),
        useNA="ifany")
    

    This gives

        0 1 2 10 20 200 <NA>
      1 3 1 1  0  0   0    0
      2 0 0 0  3  1   0    1
      3 0 0 0  0  0   3    2
      4 0 0 0  0  0   0    5
    

    ...and for your df.2:

        0 1 2 <NA>
      1 5 0 0    0
      2 0 5 0    0
      3 0 0 5    0
      4 0 0 0    5
    

    Well, this is a solution unless you really like having a list of tables for some reason.

    0 讨论(0)
  • 2021-01-22 04:47

    I think the problem is stated in applys help:

    ... If n equals 1, apply returns a vector if MARGIN has length 1 and an array of dimension dim(X)[MARGIN] otherwise ...

    The inconsistencies of the return values of base R's apply family is the reason why I shifted completely to plyrs **ply functions. So this works as desired:

    library(plyr)
    alply( df.2[ 4:8 ], 1, function(x) table( unlist(x), useNA = "ifany" ) )
    
    0 讨论(0)
  • 2021-01-22 04:58

    You can use lapply to systematically output a list. You would have to loop over the row indices:

    sub.df <- as.matrix(df.2[grepl("year", names(df.2))])
    lapply(seq_len(nrow(sub.df)), 
           function(i)table(sub.df[i, ], useNA = "ifany"))
    
    0 讨论(0)
  • 2021-01-22 04:59

    Protect the result by wrapping with list:

    apply(tdf.2[4:nrow(tdf.2),1:nrow(df.2)], 2, 
                  function(x) {list(table(x, useNA = "ifany")) })
    
    0 讨论(0)
提交回复
热议问题