理解table()的输出

时间:2014-08-17 08:16:14

标签: r

我有这个数据框

df <- data.frame(country = c("Italy", "Germany", "Italy", "USA","Poland"),
                 gender = c("male", "female", "female", "female", NA))

我希望在不同的数据框中汇总,这些数据框总结了每列中的女性和男性的数量,例如

df_result <- data.frame(country = c("Germany","Italy","Poland","USA","<NA>"),
                        female = c(1,1,0,1,0),
                        male = c(0,1,0,0,0),
                        "NA" = c(0,0,1,0,0))

as.data.frame(table(df, useNA = "always"))
   country gender Freq
1  Germany female    1
2    Italy female    1
3   Poland female    0
4      USA female    1
5     <NA> female    0
6  Germany   male    0
7    Italy   male    1
8   Poland   male    0
9      USA   male    0
10    <NA>   male    0
11 Germany   <NA>    0
12   Italy   <NA>    0
13  Poland   <NA>    1
14     USA   <NA>    0
15    <NA>   <NA>    0

1 个答案:

答案 0 :(得分:0)

 df$gender <- as.character(df$gender)
 df$gender[is.na(df$gender)] <- "NA."
 as.data.frame.matrix(table(df))
 #       female male NA.
 #Germany      1    0   0
 #Italy        1    1   0
 #Poland       0    0   1
 #USA          1    0   0