length() function in R Programming Language is used to get or set the length of a vector (list) or other objects.
Getting the length of object in R Programming
Here we are going to get the length of the vector in R Programming, for this we will use length() function.
Syntax: length(x)
Parameters:
Example 1: Getting the length of the vector
R
x <- c (6)
y <- c (1, 2, 3, 4, 5)
length (x)
length (y)
|
Output :
[1] 1
[1] 5
Example 2: Getting the length of the matrix
R
A = matrix (
c (1, 2, 3, 4, 5, 6, 7, 8, 9),
nrow = 3,
ncol = 3,
byrow = TRUE
)
print (A)
length (A)
|
Output:
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
9
Example 3: Getting the length of the Dataframe
Here BOD is dataframe has 6 rows and 2 columns giving the biochemical oxygen demand versus time in an evaluation of water quality. and we are going to get the length of this dataframe.
Output:
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
2
Note: If the parameter is a matrix or dataframe, it returns the number of variables:
Example 4: Getting the length of the list
R
empId = c (1, 2, 3, 4)
empName = c ( "Debi" , "Sandeep" , "Subham" , "Shiba" )
numberOfEmp = 4
empList = list (empId, empName, numberOfEmp)
print (empList)
print ( "Length of the list:" )
length (empList)
|
Output:
[[1]]
[1] 1 2 3 4
[[2]]
[1] "Debi" "Sandeep" "Subham" "Shiba"
[[3]]
[1] 4
[1] "Length of the list:"
3
Example 5: Getting the length of the string
In R Language, we can not easily get the length of the string, first, we have to get the character of the string using split and then unlist each character to count the length.
R
string <- "Geeks For Geeks"
length (string)
length ( unlist ( strsplit (string, "" )))
|
Output:
1
15
Setting length of the object in R Programming
Here we are going to set the length of the vector in R Programming, for this we will use length() function.
Syntax: length(x) <- value
Parameters:
R
x <- c (3)
y <- c (1, 2, 3, 4, 5)
z <- c (1, 2, 3, 4, 5)
length (x) <- 2
length (y) <- 7
length (z) <- 3
x
y
z
|
Output:
[1] 3 NA
[1] 1 2 3 4 5 NA NA
[1] 1 2 3