【问题标题】:Create a function to find the length of a vector WITHOUT using length()创建一个函数来查找向量的长度而不使用 length()
【发布时间】:2023-01-27 21:10:47
【问题描述】:

我已经尝试过 max(seq_along(x)),但如果我们输入 numeric(0),我需要它也返回 0。

所以是的,它适用于除 numeric(0) 以外的任何其他东西。这是我到目前为止所拥有的:

my_length <- function(x){
  max(seq_along(x))
}

【问题讨论】:

  • @RitchieSacramento 不允许使用尾巴:(
  • 编辑您的问题,您还有哪些其他限制?假设,头是不允许的,对吧?
  • 正如您所注意到的,seq_along() 对空向量除外。所以只需添加一个 if 来测试输入是否为空。

标签: r


【解决方案1】:

使用for循环:

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

另外的选择:

my_length <- function(x) nrow(matrix(x))

【讨论】:

    【解决方案2】:

    您可以在尝试中将 0 添加到 max() 调用中:

    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
    

    【讨论】:

      【解决方案3】:

      这里还有一些functional programming的方法:

      1. 使用映射求和:

        length = function (x) {
            sum(vapply(x, (.) 1L, integer(1L)))
        }
        
      2. 使用减少:

        length = function (x) {
            Reduce((x, .) x + 1L, x, 0L)
        }
        
      3. 使用递归:

        length = function (x, len = 0L) {
            if (is_empty(x)) len else Recall(x[-1L], len + 1L)
        }
        

        las,最后一个需要定义辅助函数,不幸的是,如果不使用length(),这就不是微不足道的了:

        is_empty = function (x) {
            is.null(x) || identical(x, vector(typeof(x), 0L))
        }
        

      【讨论】:

        【解决方案4】:

        您可以使用NROW()。从文档中:

        nrow 和 ncol 返回 x 中存在的行数或列数。 NCOL 和 NROW 将矢量视为 1 列矩阵,甚至是 0 长度矢量......


        len <- (x) NROW(x)
        

        例子:

        len(numeric(0))
        #> [1] 0
        
        len(letters)
        #> [1] 26
        
        len(c(3, 0, 9, 1))
        #> [1] 4
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多