string 如何在R中找到字符串的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11134812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the length of a string in R
提问by Igor Chubin
How to find the length of a string (number of characters in a string) without splitting it in R? I know how to find the length of a list but not of a string.
如何找到字符串的长度(字符串中的字符数)而不在 R 中拆分它?我知道如何找到列表的长度而不是字符串的长度。
And what about Unicode strings? How do I find the length (in bytes) and the number of characters (runes, symbols) in a Unicode string?
那么 Unicode 字符串呢?如何在 Unicode 字符串中找到长度(以字节为单位)和字符数(符文、符号)?
Related Question:
相关问题:
回答by Gavin Simpson
See ?nchar
. For example:
见?nchar
。例如:
> nchar("foo")
[1] 3
> set.seed(10)
> strn <- paste(sample(LETTERS, 10), collapse = "")
> strn
[1] "NHKPBEFTLY"
> nchar(strn)
[1] 10
回答by bartektartanus
Use stringi
package and stri_length
function
使用stringi
包和stri_length
函数
> stri_length(c("ala ma kota","ABC",NA))
[1] 11 3 NA
Why? Because it is the FASTEST among presented solutions :)
为什么?因为它是提出的解决方案中最快的 :)
require(microbenchmark)
require(stringi)
require(stringr)
x <- c(letters,NA,paste(sample(letters,2000,TRUE),collapse=" "))
microbenchmark(nchar(x),str_length(x),stri_length(x))
Unit: microseconds
expr min lq median uq max neval
nchar(x) 11.868 12.776 13.1590 13.6475 41.815 100
str_length(x) 30.715 33.159 33.6825 34.1360 173.400 100
stri_length(x) 2.653 3.281 4.0495 4.5380 19.966 100
and also works fine with NA's
并且也适用于 NA
nchar(NA)
## [1] 2
stri_length(NA)
## [1] NA
回答by johannes
You could also use the stringr
package:
你也可以使用这个stringr
包:
library(stringr)
str_length("foo")
[1] 3
回答by Thomas Buhl
The keepNA = TRUE option prevents problems with NA
keepNA = TRUE 选项可防止 NA 出现问题
nchar(NA)
## [1] 2
nchar(NA, keepNA=TRUE)
## [1] NA
回答by Jonathan
nchar(YOURSTRING)
you may need to convert to a character vector first;
您可能需要先转换为字符向量;
nchar(as.character(YOURSTRING))