R length Function


length() function gets or sets the length of a vector (list) or other objects.

Get vector length:

>x <- c(1,2,5,4,6,1,22,1)
>length(x)
[1] 8

Set vector length:
>length(x) <- 4
>x
[1] 1 2 5 4

Get the length of a list:
>y <- list(batch=3,label="Lung Cancer Patients", subtype=c("A","B","C"))
>y
$batch
[1] 3

$label
[1] "Lung Cancer Patients"

$subtype
[1] "A" "B" "C"
>is.list(y)
[1] TURE


>length(y)
[1] 3

If the parameter is a matrix or dataframe, it returns the number of variables:
>length(BOD)
[1] 2

>BOD
  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

When resets a list or matrix, if the list is shortened, extra values will be discarded, if the list is lengthened, NAs (or nul) is added to the list.
> length(BOD) <- 1
> BOD
$Time
[1] 1 2 3 4 5 7

> length(BOD) <- 3
> BOD
$Time
[1] 1 2 3 4 5 7

$demand
[1]  8.3 10.3 19.0 16.0 15.6 19.8

[[3]]
NULL

length() function can be used for all R objects. For an environment it returns the object number in it. NULL returns 0. Most other objects return length 1.