考慮這個角色
mystring <- "this, this and this, and this, and this."
我想拆分,或and但我想擺脫空字串。我對下面的解決方案不起作用這一事實感到困惑
拆分作業正常
> str_split(mystring, regex(',|and'))
[[1]]
[1] "this" " this " " this" " " " this" " " " this."
過濾不起作用
> str_split(mystring, regex(',|and')) %>% purrr::keep(., function(x) x!= '')
Error: Predicate functions must return a single `TRUE` or `FALSE`, not a logical vector of length 7
Run `rlang::last_error()` to see where the error occurred.
這里有什么問題?謝謝!
uj5u.com熱心網友回復:
如果我們只回傳空白 ( "") 而不是空格 ( " "),那么我們可以利用nzchar
library(purrr)
library(stringr)
str_split(mystring, regex('\\s*,\\s*|\\s*and\\s*'))[[1]] %>%
keep(nzchar)
[1] "this" "this" "this" "this" "this."
如果我們使用的是 OP 的代碼,請trimws在keep步驟之前使用
str_split(mystring, regex(',|and')) %>%
pluck(1) %>%
trimws %>%
keep(nzchar)
[1] "this" "this" "this" "this" "this."
在 OP 的代碼中, thekeep不起作用,因為來自的物件str_split是 alist并且未提取元素。因此,當我們應用該函式時,它會為單個list元素回傳多個 TRUE/FALSE,而keep期望單個 TRUE/FALSE。在這里,我們正在pluck使用串列元素。在第一個解決方案中,提取是通過[[1]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/312501.html
上一篇:從字串中提取字母和數字
