【问题标题】:join several tables together将几个表连接在一起
【发布时间】:2021-03-31 11:34:39
【问题描述】:

我有几个表格来运行我的数据的频率和百分比:

tableAge1 <- table(data$Age)
tableAge2 <- round(prop.table(tableAge1) * 100, 2)
tableGender1 <- table(data$Gender)
tableGender2 <- round(prop.table(tableGender1) * 100, 2)

结果:

18-24 25-29 30-34 35-39
    2     1     1     2

18-24 25-29 30-34 35-39
15.38  7.69  7.69 15.38

Male Female Not_Answer
   3      8          1

Male Female Not_Answer
23.08  69.23      7.69

我想像这样将这些表连接在一起:

18-24 25-29 30-34 35-39 18-24 25-29 30-34 35-39 Male Female Not_Answer
    2     1     1     2 15.38  7.69  7.69 15.38    3      8          1

有没有办法做到这一点?

bind_rows() 接近但将每个分类变量的数据添加到单独的行中:

> bind_rows(tableAge1, tableAge2, tableGender1)
# A tibble: 3 x 10
  `18-24` `25-29` `30-34` `35-39` `40-44` `50-54` `65-69` Female  Male    `Prefer not to answer`
  <table> <table> <table> <table> <table> <table> <table> <table> <table> <table>               
1  2.00   1.00    1.00     2.00    2.00    4.00   1.00    NA      NA      NA                    
2 15.38   7.69    7.69    15.38   15.38   30.77   7.69    NA      NA      NA                    
3    NA     NA      NA       NA      NA      NA     NA     9       3       1 

【问题讨论】:

  • 你需要cbind(tableAge1,tableAge2,tableGender1)吗?
  • cbind 倾向于将每个新的分类变量添加为新行。 IE。年龄结果出现在第 1 行,性别出现在第 2 行。我需要它们在同一行
  • class(tableAge1) 是什么?如果班级是“桌子”,似乎对我有用
  • 类(tableAge1)是“表”
  • 抱歉,bind_rows(tableAge1, tableAge2, tableGender1) 将每个分类变量的数据添加到单独的行中

标签: r merge


【解决方案1】:

在这里找到了解决方案: using-dplyr-to-create-summary-proportion-table

我没有尝试合并表,而是在原始数据源上使用 group_by 来汇集分类变量,然后运行统计信息:

table <- data %>%
  gather(variable, value, Age, Gender, Income) %>%
  group_by(variable, value) %>%
  summarise (n = n()) %>%
  mutate(freq = (n / sum(n)) * 100)

> table
# A tibble: 16 x 4
# Groups:   variable [3]
   variable value                      n  freq
   <chr>    <chr>                  <int> <dbl>
 1 Age      "18-24"                    2 15.4 
 2 Age      "25-29"                    1  7.69
 3 Age      "30-34"                    1  7.69
 4 Age      "35-39"                    2 15.4 
 5 Age      "40-44"                    2 15.4 
 6 Age      "50-54"                    4 30.8 
 7 Age      "65-69"                    1  7.69
 8 Gender   "Female"                   9 69.2 
 9 Gender   "Male"                     3 23.1 
10 Gender   "Prefer not to answer"     1  7.69
11 Income   ""                         3 23.1 
12 Income   "$125-$150k"               1  7.69
13 Income   "$150-$175k"               2 15.4 
14 Income   "$200-$225k"               2 15.4 
15 Income   "$250k+"                   2 15.4 
16 Income   "$75-$100k"                3 23.1 
> 

【讨论】:

    猜你喜欢
    • 2011-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 2012-11-16
    • 2013-06-30
    相关资源
    最近更新 更多