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

使用str_split用数字范围和多个数字填充数据框中的行

  •  0
  • prayner  · 技术社区  · 5 年前

    具有不同格式的FAO代码的数据帧片段。

    > FAOCODE_crops
          SPAM_full_name                          FAOCODE
    1              wheat                               15
    2               rice                               27
    8      other cereals 68,71,75,89,92,94,97,101,103,108
    27   other oil crops                  260:310,312:339
    31 other fibre crops                          773:821
    

    unlist(lapply(unlist(strsplit(FAOCODE_crops$FAOCODE, ",")), function(x) eval(parse(text = x))))
    [1]  15  27  56  44  79  79  83  68  71  75  89  92  94  97 101 103 108
    

    ... 但我没能将这些数字合并回数据帧,每个FAOCODE都有自己的行。

    > FAOCODE_crops$FAOCODE <- unlist(lapply(unlist(strsplit(MAPSPAM_crops$FAOCODE, ",")), function(x) eval(parse(text = x))))
    Error in `$<-.data.frame`(`*tmp*`, FAOCODE, value = c(15, 27, 56, 44,  : 
      replacement has 571 rows, data has 42
    

    我完全理解它为什么不能成功合并,但我想不出一种方法来为每个FAOCODE填充一个新行,如下所示:

    SPAM_full_name                          FAOCODE
    1              wheat                               15
    2               rice                               27
    8      other cereals                               68
    8      other cereals                               71
    8      other cereals                               75
    8      other cereals                               89
    

    等等。。。

    0 回复  |  直到 5 年前
        1
  •  0
  •   www    5 年前

    separate_rows 分离 , . 在那之后,我们可以通过 FAOCODE map ~eval(parse(text = .x)) 计算数字范围。最后,我们可以用 unnest 展开数据帧。

    library(tidyverse)
    
    dat2 <- dat %>%
      separate_rows(FAOCODE, sep = ",") %>%
      mutate(FAOCODE = map(FAOCODE, ~eval(parse(text = .x)))) %>%
      unnest(cols = FAOCODE)
    dat2
    # # A tibble: 140 x 2
    #    SPAM_full_name FAOCODE
    #    <chr>            <dbl>
    #  1 wheat               15
    #  2 rice                27
    #  3 other cereals       68
    #  4 other cereals       71
    #  5 other cereals       75
    #  6 other cereals       89
    #  7 other cereals       92
    #  8 other cereals       94
    #  9 other cereals       97
    # 10 other cereals      101
    # # ... with 130 more rows
    

    数据

    dat <- read.table(text = "      SPAM_full_name                          FAOCODE
    1              wheat                               15
    2               rice                               27
    8      'other cereals' '68,71,75,89,92,94,97,101,103,108'
    27   'other oil crops'                  '260:310,312:339'
    31 'other fibre crops'                          '773:821'",
                      header = TRUE, stringsAsFactors = FALSE)
    
    推荐文章