将零长度字符向量作为空字符串处理

通过示例,请参阅下面的Twitter句柄摘录。目标是具有一个类似于tweets但只有句柄用逗号分隔的字符串。如果没有找到匹配项,str_replace_all会产生空向量,并在跟踪过程中引发一些意外错误。

library(purrr)
library(stringr)

tweets <- c(
  "","This tweet has no handles","This is a tweet for @you","This is another tweet for @you and @me","This,@bla,is another tweet for @me and @you"
)


mention_rx <- "@\\w+"

这是我的第一次尝试:

map_chr(tweets,~str_c(str_extract_all(.x,mention_rx)[[1]],collapse = ","))
#> Error: Result 1 must be a single string,not a character vector of length 0

然后我玩弄一些东西:

mentions <- map(tweets,"))

mentions
#> [[1]]
#> character(0)
#> 
#> [[2]]
#> character(0)
#> 
#> [[3]]
#> [1] "@you"
#> 
#> [[4]]
#> [1] "@you,@me"
#> 
#> [[5]]
#> [1] "@bla,@me,@you"

as.character(mentions)
#> [1] "character(0)"    "character(0)"    "@you"            "@you,@me"      
#> [5] "@bla,@you"

直到我意识到paste也可以在这里使用:

map_chr(tweets,~paste(str_extract_all(.x,"))
#> ""                ""                "@you"            "@you,@me"       "@bla,@you"

我的问题是:

  • 到达那里是否有更优雅的方式?
  • 为什么str_c的行为与paste相同,却具有相同的collapse参数?
  • 为什么as.charactermap_chr无法识别字符向量 长度为零,等于一个空字符串,但是paste呢?

我在str(i)_cpastedifference between them上找到了很好的参考;但是这些都不用空字符串解决这种情况。

wenm2009 回答:将零长度字符向量作为空字符串处理

您不需要map超过tweetsstr_extract_all可以处理向量

library(stringr)
str_extract_all(tweets,mention_rx)

#[[1]]
#character(0)

#[[2]]
#character(0)

#[[3]]
#[1] "@you"

#[[4]]
#[1] "@you" "@me" 

#[[5]]
#[1] "@bla" "@me"  "@you"

现在,如果您需要一个逗号分隔的字符串,则可以使用map

purrr::map_chr(str_extract_all(tweets,mention_rx),toString)
#[1] ""    ""      "@you"     "@you,@me"      "@bla,@me,@you"

要回答“为什么”问题,我们可以查看pastestr_c函数的文档。

来自?paste

  

向量参数将根据需要进行回收,零长度参数将被回收为“”。

来自?str_c

  

零长度参数被删除。

因此,默认情况下,str_c会删除零长度的参数,这会使输出成为0长度的字符串,该字符串对于map_chr会失败,但是它会与map一起使用,因为map返回列表

map(tweets,~str_c(str_extract_all(.x,mention_rx)[[1]],collapse = ","))

#[[1]]
#character(0)

#[[2]]
#character(0)

#[[3]]
 #[1] "@you"

#[[4]]
#[1] "@you,@me"

#[[5]]
#[1] "@bla,@you"
本文链接:https://www.f2er.com/3162554.html

大家都在问