nchar() method in R Programming Language is used to get the length of a character in a string object.
Syntax: nchar(string)
Where: String is object.
Return: Returns the length of a string.
In this example, we are going to see how to get the length of a string object using nchar() method.
# R program to calculate length of string # Given String gfg < - "Geeks For Geeks" # Using nchar() method answer < - nchar(gfg) print(answer)
Output:
[1] 15
In this example, we will get the length of the vector using nchar() method.
# 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)
Output:
'character' 5 1 5 2
The nchar() function provides an optional argument called keepNA, it can help when dealing with NA values.
# R program to create Character Vectors # by default numeric values # are converted into characters v1 <- c(NULL, '2', 'hello', NA) nchar(v1, keepNA = FALSE)
Output:
1 5 2
In the above example, the first element is NULL then it returns nothing and the last element NA returns 2 because we keep keepNA = FALSE. If we pass keepNA = TRUE, then see the following output:
# R program to create Character Vectors # by default numeric values # are converted into characters v1 <- c('', NULL, 'hello', NA) nchar(v1, keepNA = TRUE)
Output:
0 5
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.