代码之家  ›  专栏  ›  技术社区  ›  Ed_Gravy

R转换TIBLE列表的数据类型

  •  1
  • Ed_Gravy  · 技术社区  · 4 年前

    与此类似 question ,我也想这样做,但要列出 tibbles .

    我该怎么做?

    样本数据(&A);代码:

    library(tidyverse)
    
    tbl1 = tibble(x = c('a', 'b', 'c'), y = 1:3)
    tbl2 = tibble(x = c('11', '12', '13'), y = 1:3)
    
    tbl = list(tbl1, tbl2)
    
    data_types = rep(c("character"),times = 3)
    
    tbl[] = map2(tbl, str_c("as.", data_types), ~ get(.y)(.x))
    

    错误:

    Error: Mapped vectors must have consistent lengths:
    * `.x` has length 2
    * `.y` has length 3
    
    1 回复  |  直到 4 年前
        1
  •  3
  •   akrun    4 年前

    在链接帖子中,它具有不同的列类型,因此我们创建了一个类型向量,其长度等于数据中的列数。在这里,中每个数据集中的列数 list rep 具有 times 2

    data_types <- rep(c("character"),times = 2)
    

    此外,由于我们必须在列表上循环,请执行嵌套 map/map2

    library(purrr)
    map(tbl, ~ map2_dfr(.x, str_c("as.", data_types), ~ get(.y)(.x)))
    

    或者因为只有一种类型,我们也可以这样做

    map(tbl,  ~map_dfr(.x, as.character)) 
    

    -输出

    [[1]]
    # A tibble: 3 × 2
      x     y    
      <chr> <chr>
    1 a     1    
    2 b     2    
    3 c     3    
    
    [[2]]
    # A tibble: 3 × 2
      x     y    
      <chr> <chr>
    1 11    1    
    2 12    2    
    3 13    3    
    
    推荐文章