Table by row with R

前端 未结 4 1472
暗喜
暗喜 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 
      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 
      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.

提交回复
热议问题