R语言 寻找字符串的长度 – nchar()方法
R编程语言中的ncar()方法 是用来获取字符串对象中的一个字符的长度。
语法: ncar(string)
其中: 字符串是对象。
返回: 返回一个字符串的长度。
R语言–使用ncar()方法获取字符串的长度 示例
例1:在 R 中查找字符串的长度
在这个例子中,我们将看到如何使用ncar()方法获得一个字符串对象的长度。
# R program to calculate length of string
# Given String
gfg < - "Geeks For Geeks"
# Using nchar() method
answer < - nchar(gfg)
print(answer)
输出
[1] 15
例2: 对R向量使用ncar
在这个例子中,我们将使用ncar()方法获得向量的长度。
# R program to get length of Character Vectors
# by default numeric values
# are converted into characters
v1 <- c('geeks', '2', 'hello', 57)
# Displaying type of vector
typeof(v1)
nchar(v1)
输出
'character'
5 1 5 2
例3:向ncar()函数传递NA值
nchar()函数提供了一个可选的参数,叫做keepNA,它可以在处理NA值的时候提供帮助。
# R program to create Character Vectors
# by default numeric values
# are converted into characters
v1 <- c(NULL, '2', 'hello', NA)
nchar(v1, keepNA = FALSE)
输出
1 5 2
在上面的例子中,第一个元素是NULL,那么它没有返回任何东西,最后一个元素NA返回2,因为我们保持keepNA = FALSE。如果我们传递keepNA = TRUE,那么请看下面的输出。
# R program to create Character Vectors
# by default numeric values
# are converted into characters
v1 <- c('', NULL, 'hello', NA)
nchar(v1, keepNA = TRUE)
输出
0 5 <NA>