简体   繁体   English

多个数据透视表 - R(表)

[英]Multiple Pivot Table - R (table)

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. 我想在R中做一个转轴,找出每个州的每种类型的数量。

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? 有谁知道怎么做这样的事情?

You can use reshape2 to reshape your data into the correct format: 您可以使用reshape2将数据重塑为正确的格式:

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

Use dplyr 使用dplyr

    library(dplyr)

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

table can handle multiple variables. table可以处理多个变量。

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

Use addmargins to get the totals. 使用addmargins获取总数。

## 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM