R计数的逗号和字符串 [英] R count number of commas and string

查看:66
本文介绍了R计数的逗号和字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:

    str1 <- "This is a string, that I've written 
        to ask about a question, or at least tried to."

我会如何:

1)计算逗号数

2)计算"-ion"的出现

2) count the occurences of '-ion'

有什么建议吗?

推荐答案

stringr软件包具有函数str_count,可以很好地为您完成此任务.

The stringr package has a function str_count that does this for you nicely.

library(stringr)

str_count(str1, ',')
[1] 2
str_count(str1, 'ion')
[1] 1

因为我很好奇:

vec <- paste(sample(letters, 1e6, replace=T), collapse=' ')

system.time(str_count(vec, 'a'))
   user  system elapsed 
  0.052   0.000   0.054 

system.time(length(gregexpr('a', vec, fixed=T)[[1]]))
   user  system elapsed 
  2.124   0.016   2.146 

system.time(length(gregexpr('a', vec, fixed=F)[[1]]))
   user  system elapsed 
  0.052   0.000   0.052 

这篇关于R计数的逗号和字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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