R 递归拆分列表元素

R 递归拆分列表元素,r,R,我找不到正确的咒语Reduce、Recall、lappy来执行以下任务。考虑下面的函数, bisect.df <- function(d){ n <- ncol(d) if(n%%2) n <- n-1 # drop one col if odd number ind <- sample(n)[seq.int(n/2)] # split randomly both parts list(first=d[, ind], second=d[,

我找不到正确的咒语Reduce、Recall、lappy来执行以下任务。考虑下面的函数,

bisect.df <- function(d){
  n <- ncol(d)
  if(n%%2) n <- n-1 # drop one col if odd number
  ind <- sample(n)[seq.int(n/2)] # split randomly both parts

  list(first=d[, ind],
       second=d[, -ind])
}
但是我如何递归地称之为N=3次呢

这是一个测试样本

d <- data.frame(matrix(rnorm(16*5), ncol=16))
step1 <- bisect.list(list(d))
step2 <- bisect.list(step1)
step3 <- bisect.list(step2)
str(list(step1, step2, step3))

不知道如何在没有循环的情况下执行…

这里有一个递归解决方案:其思想是添加一个参数,计算剩余递归调用的数量。但它的功能与循环版本完全相同

f <- function( d, n=3 ) {
  if( is.data.frame( d ) )
    return( f( list(d), n ) )
  if( n == 0 )
    return( d )
  result <- lapply( d, bisect.df )
  result <- unlist( result, recursive=FALSE )
  result <- f( result, n-1 )
  result
}
d <- as.data.frame( t(1:20) )
f(d)
随机获取列索引可能更容易
然后一次构建所有的子data.frames。

我的意思是不使用for循环,以增加趣味性。但是你得到+1,因为它完成了任务:好的一点,事实上,我的原始问题从每个级别的第一个data.frame采样可能更有意义。
bisect.list <- function(l,n){
  for(i in 1:n) {
    l <- unlist(lapply(l, bisect.df), recursive=FALSE)
  }
  return(l)
}
f <- function( d, n=3 ) {
  if( is.data.frame( d ) )
    return( f( list(d), n ) )
  if( n == 0 )
    return( d )
  result <- lapply( d, bisect.df )
  result <- unlist( result, recursive=FALSE )
  result <- f( result, n-1 )
  result
}
d <- as.data.frame( t(1:20) )
f(d)