【问题标题】:how to filter only vectors that contain all uppercase letters in all the strings in R如何仅过滤包含R中所有字符串中所有大写字母的向量
【发布时间】:2020-07-20 15:47:48
【问题描述】:

我需要过滤 R 中大写的行。我设法使用了以下代码:

filter(str_detect(fruit, "^[:upper:]+$"))

但是,“fruit”列的某些值包含两个或三个字符串,上面的代码仅适用于只有一个字符串的情况。我无法共享数据,但此示例适用于我的目的(仅 str_detect 部分)

fruit <- c("apple", "ORANGE", "kiwi" ,"TWO PEARS", "A BIG PINEAPPLE", "LEMON")
str_detect(fruit, "^[:upper:]+$")
[1] FALSE  TRUE FALSE FALSE FALSE  TRUE

我想要的是也能够识别“两个梨”和“一个大菠萝”。你能帮帮我吗?

非常感谢!

【问题讨论】:

  • 你能否定寻找小写的结果吗?

标签: r string dplyr


【解决方案1】:

尝试包含空格字符类。

stringr::str_detect(fruit, "^[[:upper:][:space:]]+$")
#[1] FALSE  TRUE FALSE  TRUE  TRUE  TRUE

comment 之后,否定大写:

stringr::str_detect(fruit, "^[^[:lower:]]+$")
#[1] FALSE  TRUE FALSE  TRUE  TRUE  TRUE

【讨论】:

  • 谢谢,@Rui Barradas 成功了!我用了 !否定大写的表达式:filter(!str_detect(fruit, "^[:upper:]+$")),但我更喜欢你的解决方案。
【解决方案2】:

我们可以在base R中使用grep

grep("^[A-Z ]+$", fruit, value = TRUE)
#[1] "ORANGE"          "TWO PEARS"       "A BIG PINEAPPLE" "LEMON"   

获取其他元素

grep("^[A-Z ]+$", fruit, value = TRUE, inverse = TRUE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-10
    • 2021-12-31
    • 1970-01-01
    • 2012-03-07
    • 2018-07-08
    • 2018-10-12
    • 2018-04-03
    • 1970-01-01
    相关资源
    最近更新 更多