如何拆分和过滤字符串?
how to split and filter a string?
考虑这个角色
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.
这里有什么问题?
谢谢!
如果我们return只有空格(""
)而不是空格(" "
),那么我们可以利用nzchar
library(purrr)
library(stringr)
str_split(mystring, regex('\s*,\s*|\s*and\s*'))[[1]] %>%
keep(nzchar)
[1] "this" "this" "this" "this" "this."
如果我们使用 OP 的代码,请在 keep
步骤之前使用 trimws
str_split(mystring, regex(',|and')) %>%
pluck(1) %>%
trimws %>%
keep(nzchar)
[1] "this" "this" "this" "this" "this."
在 OP 的代码中,keep
不起作用,因为 str_split
中的对象是 list
并且未提取元素。因此,当我们应用该函数时,它 return 是单个 list
元素的多个 TRUE/FALSE,而 keep
期望单个 TRUE/FALSE。在这里,我们正在 pluck
ing 列表元素。在第一个解决方案中,提取是由 [[1]]
完成的
考虑这个角色
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.
这里有什么问题? 谢谢!
如果我们return只有空格(""
)而不是空格(" "
),那么我们可以利用nzchar
library(purrr)
library(stringr)
str_split(mystring, regex('\s*,\s*|\s*and\s*'))[[1]] %>%
keep(nzchar)
[1] "this" "this" "this" "this" "this."
如果我们使用 OP 的代码,请在 keep
步骤之前使用 trimws
str_split(mystring, regex(',|and')) %>%
pluck(1) %>%
trimws %>%
keep(nzchar)
[1] "this" "this" "this" "this" "this."
在 OP 的代码中,keep
不起作用,因为 str_split
中的对象是 list
并且未提取元素。因此,当我们应用该函数时,它 return 是单个 list
元素的多个 TRUE/FALSE,而 keep
期望单个 TRUE/FALSE。在这里,我们正在 pluck
ing 列表元素。在第一个解决方案中,提取是由 [[1]]