计算R中字符串(不包括空格)中的字符?

4 string r character gsub

我想计算一个字符串中的字符数(不包括空格),我想知道我的方法是否可以改进.

假设我有:

x <- "hello to you"
Run Code Online (Sandbox Code Playgroud)

我知道nchar()会给我一个字符串中的字符数(包括空格):

> nchar(x)
[1] 12
Run Code Online (Sandbox Code Playgroud)

但是我想返回以下内容(不包括空格):

[1] 10
Run Code Online (Sandbox Code Playgroud)

为此,我做了以下事情:

> nchar(gsub(" ", "",x))
[1] 10
Run Code Online (Sandbox Code Playgroud)

我担心的是gsub()许多字符串会花费很长时间.这是接近这个的正确方法,还是有一种nchar'esque函数会返回字符数而不计算空格?

提前致谢.

A5C*_*2T1 7

在Richard的评论的基础上,"stringi"将是一个很好的考虑因素:

方法可以是计算整个字符串长度并减去空格数.

比较以下内容.

library(stringi)
library(microbenchmark)

x <- "hello to you"
x
# [1] "hello to you"
fun1 <- function(x) stri_length(x) - stri_count_fixed(x, " ")
fun2 <- function(x) nchar(gsub(" ", "",x))
y <- paste(as.vector(replicate(1000000, x, TRUE)), collapse = "     ")

microbenchmark(fun1(x), fun2(x))
# Unit: microseconds
#     expr   min    lq     mean median      uq    max neval
#  fun1(x) 5.560 5.988  8.65163  7.270  8.1255 44.047   100
#  fun2(x) 9.408 9.837 12.84670 10.691 12.4020 57.732   100
microbenchmark(fun1(y), fun2(y), times = 10)
# Unit: milliseconds
#     expr        min         lq      mean     median         uq        max neval
#  fun1(y)   68.22904   68.50273   69.6419   68.63914   70.47284   75.17682    10
#  fun2(y) 2009.14710 2011.05178 2042.8123 2030.10502 2079.87224 2090.09142    10
Run Code Online (Sandbox Code Playgroud)

  • @ChuckD.,现在你知道microbenchmark,你应该能够自己测试我以前的评论:-) (2认同)