如何计算给定字符在一列字符串的每一行中出现的次数? [英] How to calculate the number of occurrence of a given character in each row of a column of strings?

查看:25
本文介绍了如何计算给定字符在一列字符串的每一行中出现的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 data.frame,其中某些变量包含一个文本字符串.我希望计算每个字符串中给定字符的出现次数.

I have a data.frame in which certain variables contain a text string. I wish to count the number of occurrences of a given character in each individual string.

例子:

q.data<-data.frame(number=1:3, string=c("greatgreat", "magic", "not"))

我希望为 q.data 创建一个新列,其中包含字符串中a"的出现次数(即 c(2,1,0)).

I wish to create a new column for q.data with the number of occurence of "a" in string (ie. c(2,1,0)).

我管理过的唯一复杂的方法是:

The only convoluted approach I have managed is:

string.counter<-function(strings, pattern){  
  counts<-NULL
  for(i in 1:length(strings)){
    counts[i]<-length(attr(gregexpr(pattern,strings[i])[[1]], "match.length")[attr(gregexpr(pattern,strings[i])[[1]], "match.length")>0])
  }
return(counts)
}

string.counter(strings=q.data$string, pattern="a")

 number     string number.of.a
1      1 greatgreat           2
2      2      magic           1
3      3        not           0

推荐答案

stringr 包提供了 str_count 函数,似乎可以做你感兴趣的事情

The stringr package provides the str_count function which seems to do what you're interested in

# Load your example data
q.data<-data.frame(number=1:3, string=c("greatgreat", "magic", "not"), stringsAsFactors = F)
library(stringr)

# Count the number of 'a's in each element of string
q.data$number.of.a <- str_count(q.data$string, "a")
q.data
#  number     string number.of.a
#1      1 greatgreat           2
#2      2      magic           1
#3      3        not           0

这篇关于如何计算给定字符在一列字符串的每一行中出现的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆