【问题标题】:How to calculate the number of occurrence of a given NUMBER in each row of a column of strings?如何计算给定NUMBER在一列字符串的每一行中出现的次数?
【发布时间】:2019-06-14 19:44:00
【问题描述】:

我有一个 data.frame,其中某些变量包含一个文本字符串。我的目标是计算每个单独字符串中给定 NUMBER 的唯一出现次数。

其他帖子表明这可以通过纵梁完成 How to calculate the number of occurrence of a given character in each row of a column of strings? calculate the total number of occurrence of a list of keyword in a string column count number of numbers (not digits) in a string

比如... 示例 1:

q.data <- data.frame(number=1:4, 
                     string=c("1", "12", "3", "31"))

stringr::str_count(q.data$string, c("1")) 

# gives (1,1,0,1)

这给出了c(1,1,0,1)。我真正想要的是创建一个新列c(1),表示数字“1”出现了一次。然后我想扩展它以包含多个关键字,例如

示例 2:

stringr::str_count(q.data$string, c("1", "31"))

这个新列现在将是c(2),表示这些数字出现了两次。

对此的任何帮助将不胜感激。

【问题讨论】:

  • 如果你用它的结构来展示你想要的输出,它会有所帮助。

标签: r string dataframe


【解决方案1】:

你可以使用data.table:

# load library and convert to data.table
setDT(q.data)

# Count occurrences of "1":
q.data[string %in% "1", .N] # string == "1" could have been used too

# Count occurrences of values in a vector:
q.data[string %in% c("1", "31"), .N]

.N 计算行数。逗号前的表达式过滤数据。 %in% 位检查元素是否包含在另一个集合中。

查看?data.table?match 了解更多详情。

【讨论】:

    【解决方案2】:

    您可以将要检查的字符串放入列表中,然后使用sapply。不确定你想要什么输出结构,但无论如何这是一个开始 -

    checklist <- list("1", c("1", "31"))
    
    sapply(checklist, function(x) {
      sum(x %in% q.data$string)
    })
    
    [1] 1 2
    

    【讨论】:

      猜你喜欢
      • 2012-09-07
      • 1970-01-01
      • 2020-03-07
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多