通过示例,请参阅下面的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.character
和map_chr
无法识别字符向量 长度为零,等于一个空字符串,但是paste
呢?
我在str(i)_c,paste和difference between them上找到了很好的参考;但是这些都不用空字符串解决这种情况。