【问题标题】:Using str_extract_all and unnest but losing rows from NA使用 str_extract_all 和 unnest 但从 NA 丢失行
【发布时间】:2019-06-18 05:13:18
【问题描述】:

我正在使用str_extract()str_extract_all() 来查看一下正则表达式。有零个、一个或多个结果,所以我想unnest() 将多个结果分成多行。由于 ab_all 中的字符(0)(我假设),unnest 不会给出输出中的所有行。

library(tidyverse)

my_tbl <- tibble(clmn = c("abcd", "abef, abgh", "xkcd"))

ab_tbl <- my_tbl %>% 
  mutate(ab = str_extract(clmn, "(?<=ab)[:alpha:]*\\b"), 
         ab_all = str_extract_all(clmn, "(?<=ab)[:alpha:]*\\b"), 
         cd = str_extract(clmn, "[:alpha:]*(?=cd)"))

ab_tbl %>% unnest(ab_all, .drop = FALSE)
# A tibble: 3 x 4
  clmn       ab    cd    ab_all
  <chr>      <chr> <chr> <chr> 
1 abcd       cd    ab    cd    
2 abef, abgh ef    NA    ef    
3 abef, abgh ef    NA    gh 

编辑: 预期输出:

# A tibble: 3 x 4
  clmn       ab    cd    ab_all
  <chr>      <chr> <chr> <chr> 
1 abcd       cd    ab    cd    
2 abef, abgh ef    NA    ef    
3 abef, abgh ef    NA    gh 
4 xkcd       NA    xk    NA  

输出中没有给出带有 xkccd 的行。是否与 str_extract_all 或 unnest 有关,还是我应该改变我的方法?

【问题讨论】:

  • 您好 nmoorenz,您能否在您的问题中添加一个数据框,以明确您正在寻找的输出?

标签: r tidyr stringr


【解决方案1】:

也许我们可以将长度为 0 更改为 NA,然后执行 unnest

library(tidyverse)
ab_tbl %>%
    mutate(ab_all = map(ab_all,  ~ if(length(.x) ==0) NA_character_ else .x)) %>% 
     unnest

注意:假设str_extract 中的模式是正确的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-08
    • 2013-05-03
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    相关资源
    最近更新 更多