繁体   English   中英

使用str_extract_all和unnest但从NA中丢失行

[英]Using str_extract_all and unnest but losing rows from NA

我正在使用str_extract()str_extract_all()对正则表达式进行一些研究。 有零个,一个或多个结果,所以我想将多个结果unnest()分成多行。 由于ab_all中的character(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或其他消息有关吗,还是应该更改方法?

可能是我们可以将0的长度更改为NA ,然后执行unnest

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM