Multiple Pivot Table - R (table)

和自甴很熟 提交于 2021-02-11 07:46:12

问题


I have the following:

Type  State 
A     California
B     Washington
A     California
A     California
A     Washington
B     New York

I would like to do a pivot in R to find out the number of each type in each state.

I have figured out how to find out the number of each type (without state breakdown) by using:

table(df$Type)

This gives me the following result:

Var1 Freq
A    4
B    2

However, I would like to add a second dimension such that I can get a state breakdown of the above result. A suggested output would look like this:

  California  Washington New York   Total
A     3            1         0        4
B     0            1         1        2

Does anyone know how to do something like this?


回答1:


You can use reshape2 to reshape your data into the correct format:

library(reshape2)
df1 <- dcast(df, Type ~ State)

To get it in the format with the row sums as listed in your question you simply need to make a few manipulations:

# add rownames
rownames(df1) <- df1$Type
df1$Type <- NULL

# calculate rowSums
df1$Total <- rowSums(df1)

And this will have the expected output:

  California New York Washington Total
A          3        0          1     4
B          0        1          1     2



回答2:


Use dplyr

    library(dplyr)

    df %>%
      group_by(Type, State) %>%
      tally()



回答3:


table can handle multiple variables.

table(mydf)
#     State
# Type California New York Washington
#    A          3        0          1
#    B          0        1          1

Use addmargins to get the totals.

## Row totals
addmargins(table(mydf), margin = 2)
#     State
# Type California New York Washington Sum
#    A          3        0          1   4
#    B          0        1          1   2

## Row and column totals
addmargins(table(mydf))
#     State
# Type  California New York Washington Sum
#   A            3        0          1   4
#   B            0        1          1   2
#   Sum          3        1          2   6


来源:https://stackoverflow.com/questions/30419246/multiple-pivot-table-r-table

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