I already tried max(seq_along(x))
but I need it to also return 0 if we, let's say, inputted numeric(0)
.
So yeah, it works for anything else other than numeric(0). This is what I have so far:
my_length <- function(x){
max(seq_along(x))
}
CodePudding user response:
Using forloop:
my_length <- function(x){
l = 0
for(i in x) l <- l 1
return(l)
}
x <- numeric(0)
my_length(x)
# [1] 0
x <- 1:10
my_length(x)
# [1] 10
Another option:
my_length <- function(x) nrow(matrix(x))
CodePudding user response:
You can just include a 0
to the max()
call in your attempt:
my_length <- function(x) max(0, seq_along(x))
my_length(10:1)
[1] 10
my_length(NULL)
[1] 0
my_length(numeric())
[1] 0
CodePudding user response:
You can use NROW()
. From the documentation:
nrow and ncol return the number of rows or columns present in x. NCOL and NROW do the same treating a vector as 1-column matrix, even a 0-length vector ...
len <- \(x) NROW(x)
Examples:
len(numeric(0))
#> [1] 0
len(letters)
#> [1] 26
len(c(3, 0, 9, 1))
#> [1] 4
CodePudding user response:
Here are a few more functional programming approaches:
Using mapping and summation:
length = function (x) { sum(vapply(x, \(.) 1L, integer(1L))) }
Using reduction:
length = function (x) { Reduce(\(x, .) x 1L, x, 0L) }
Using recursion:
length = function (x, len = 0L) { if (is_empty(x)) len else Recall(x[-1L], len 1L) }
Alas, the last one needs to define the helper function and that is unfortunately not trivial without using
length()
:is_empty = function (x) { is.null(x) || identical(x, vector(typeof(x), 0L)) }