【问题标题】:Is there a way in R to count the number of substrings in a string enclosed in square brackets, all substrings are separated by commas and are quoted?R中有没有办法计算方括号括起来的字符串中子字符串的数量,所有子字符串都用逗号分隔并被引用?
【发布时间】:2021-11-18 01:06:36
【问题描述】:

['ax', 'byc', 'crm', 'dop']

这是一个字符串,我想要一个所有子字符串的计数,即这里的 4 作为输出。想要对包含此类字符串的整个列执行此操作。

【问题讨论】:

标签: r string character


【解决方案1】:

我们可能会使用str_count

library(stringr)
str_count(str1, "\\w+")
[1] 4

或者也可以将字母数字字符提取到list 并得到lengths

lengths(str_extract_all(str1, "[[:alnum:]]+"))

如果是data.frame列,则将该列提取为向量并应用str_count

str_count(df1$str1, "\\w+")

数据

 str1 <- "['ax', 'byc', 'crm', 'dop']"
df1 <- data.frame(str1)

【讨论】:

    【解决方案2】:

    这里有一些基本的 R 方法。我们在最后的注释中使用可重复定义的 2 行输入。不使用任何包。

    lengths(strsplit(DF$b, ","))
    ## [1] 4 4
    
    nchar(gsub("[^,]", "", DF$b)) + 1
    ## [1] 4 4
    
    count.fields(textConnection(DF$b), ",")
    ## [1] 4 4
    

    注意

    DF <- data.frame(a = 1:2, b = "['ax', 'byc', 'crm', 'dop']")
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-04-12
      • 2018-07-09
      • 2021-05-16
      • 2012-03-28
      • 1970-01-01
      相关资源
      最近更新 更多