【问题标题】:Splitting vector into n amount of lists objects (R)将向量拆分为 n 个列表对象 (R)
【发布时间】:2020-08-07 02:51:43
【问题描述】:

我正在寻找一个函数,可以将项目向量拆分为相对于我提供函数的列表大小的列表

假设我的函数一次只取 2 个项目,我想将这个向量拆分成这样

my_vector <- c(1,2,3,4,5)

# ideal function call
my_list <- obj_splitter(obj = my_vector, max_expressions = 2)

my_list
  : num [1:2] 1 2
  : num [1:2] 3 4
  : num 5

当前尝试:

obj_splitter <- function(obj, max_expressions) {
  output_list <- list()
  size <- length(obj)

  if(length(obj) <= max_expressions) {
    return(obj)
  } else if(size > max_expressions){
    if(size%%max_expressions>0) {
      obj_counter <- ceiling(size/max_expressions)
      # i am unsure how to move the items from the vector into their respective list
      return(obj_counter)
    }
  }
}

【问题讨论】:

    标签: r list vector


    【解决方案1】:

    这是你想要的吗?

    my_vector <- c(1,2,3,4,5)
    
    obj_splitter <- function(obj, max) {
      split(obj, ceiling(seq_along(obj)/max))
    }
    
    my_list <- obj_splitter(my_vector, 2)
    
    str(my_list)
    #List of 3
    # $ 1: num [1:2] 1 2
    # $ 2: num [1:2] 3 4
    # $ 3: num 5
    

    您可能仍想检查一些边缘情况。如果您希望输出不被命名,您可以将其包装在 unname 中。

    编辑:更紧凑的功能。

    【讨论】:

    • 这完美!名称并不重要,因为这将映射到所述初始函数中,所以我不在乎它们的名称
    猜你喜欢
    • 1970-01-01
    • 2014-12-27
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2020-10-17
    相关资源
    最近更新 更多