【问题标题】:Merge two table objects in order to create a new dataframe in r合并两个表对象以便在 r 中创建一个新的数据框
【发布时间】:2021-10-04 21:11:28
【问题描述】:

我有 2 个表格对象,例如:

type1:

   0    1    2    3   12   20 
1318  841    4    1    1    1


type1<- structure(c(`0` = 1318L, `1` = 841L, `2` = 4L, `3` = 1L, `12` = 1L, 
`20` = 1L), .Dim = 6L, .Dimnames = structure(list(c("0", "1", 
"2", "3", "12", "20")), .Names = ""), class = "table")

type2:

  0   1   2  12  15 
 93 178   1   4   1



type2<-structure(c(`0` = 93L, `1` = 178L, `2` = 1L, `12` = 4L, `15` = 1L
), .Dim = 5L, .Dimnames = structure(list(c("0", "1", "2", "12", 
"15")), .Names = ""), class = "table")

我想合并它们以获得数据框,例如:

x  y2     y
1  type1  841
2  type1  4
3  type1  1
4  type1  0
5+ type1  2
1  type2  178
2  type2  1
3  type2  0
4  type2  0
5+ type2  5

我将 type1 或 type2 &gt;= 5 中的所有列相加,并将此计数添加到 5+ 行中。

请问有人有什么想法吗?

【问题讨论】:

    标签: r dplyr datatable


    【解决方案1】:
    library(tidyverse)
    
    list(type1 = type1, type2 = type2) %>%
      map(~tibble(x = as.integer(names(.x)), y = .x)) %>%
      map(~complete(.x, x = 1:5, fill = list(y = 0))) %>%
      imap_dfr(~
            filter(.x, x > 0) %>%
              group_by(x = ifelse(x >= 5, "5+", x)) %>% 
              summarise(y = sum(y)) %>%
              mutate(y2 = .y)
            
      ) %>%
      select(x, y2, y)
    

    输出:

       x     y2        y
       <chr> <chr> <dbl>
     1 1     type1   841
     2 2     type1     4
     3 3     type1     1
     4 4     type1     0
     5 5+    type1     2
     6 1     type2   178
     7 2     type2     1
     8 3     type2     0
     9 4     type2     0
    10 5+    type2     5
    

    【讨论】:

    • 我收到以下消息:“map.poly 中的错误(数据库、区域、精确、xlim、ylim、边界、内部,:没有可识别的区域名称”
    • 从该错误消息中,我认为您加载了一些包含 map 函数的其他包。尝试将purrr:: 放在mapimap_dfr 之前。
    【解决方案2】:

    我会这样做(绑定然后...):

    library(dplyr)
    rbind(data.frame(y = type1, y2 = "type1"), data.frame(y = type2, y2 = "type2")) %>% 
      mutate(x = ifelse(as.numeric(as.character(y.Var1)) < 5, as.character(y.Var1), "5+")) %>% 
      group_by(x,y2) %>% 
      summarise(y = sum(y.Freq), .groups = "drop") %>% 
      arrange(y2, desc(y)) 
    # A tibble: 9 × 3
      x     y2        y
      <chr> <chr> <int>
    1 0     type1  1318
    2 1     type1   841
    3 2     type1     4
    4 5+    type1     2
    5 3     type1     1
    6 1     type2   178
    7 0     type2    93
    8 5+    type2     5
    9 2     type2     1
    

    【讨论】:

    • 没有x列和type2行看起来不像预期的那样正常吗..
    猜你喜欢
    • 2020-01-01
    • 2020-09-17
    • 2022-01-08
    • 2012-11-25
    • 2016-05-01
    • 2018-09-04
    • 2023-03-06
    • 1970-01-01
    相关资源
    最近更新 更多