【问题标题】:Keep strings of a specified length, in R在 R 中保留指定长度的字符串
【发布时间】:2018-02-26 23:21:32
【问题描述】:

我可以使用

dirs <- list.dirs("C:/Data", full.names = T, recursive = T) %>% 
strtrim(20) %>% 
unique()

要获得 20 个字符或更少的字符串,但我如何才能获得那些只有 20 个字符的字符串?

【问题讨论】:

  • 试试filter(nchar(dirs) == 20)
  • @missuse: I get Error in UseMethod("filter_") : no applicable method for 'filter_'应用于“logical”类的对象,但它被列为chr。我不明白。
  • library(tidyverse) as.tibble(dirs) %&gt;% filter(nchar(dirs) == 20) 或只是dirs[nchar(dirs) == 20] dirs 是一个字符,但nchar(dirs) == 20 是一个逻辑向量。

标签: r string directory


【解决方案1】:

您也可以使用带有正则表达式的str_detect 来执行此操作。这里的表达式^.{5}$ 表示只匹配由开头组成的字符串,然后是任何字符的 5 个,然后是字符串的结尾(5 个,因为示例单词数据集中没有 20 个字符的单词)。

library(stringr)
head(words)
#> [1] "a"        "able"     "about"    "absolute" "accept"   "account"
head(words[str_detect(words, "^.{5}$")])
#> [1] "about" "admit" "after" "again" "agent" "agree"

reprex package (v0.2.0) 于 2018 年 2 月 26 日创建。

【讨论】:

    猜你喜欢
    • 2017-07-08
    • 1970-01-01
    • 2017-09-06
    • 2011-09-04
    • 1970-01-01
    • 2015-07-10
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    相关资源
    最近更新 更多