在列表矩阵中查找正确的递归顺序

时间:2014-09-03 20:51:18

标签: r recursion matrix

这与我的另一个问题有关,可能有助于我找到解决方案。以下结构是一个3x1矩阵,每个元素都包含一个列表。

cb <- structure(list(c("apples", "and", "pears"), c("one", "banana"
      ), c("pears", "oranges", "and", "pizza")), .Dim = c(3L, 1L),   
      .Dimnames = list(NULL, "s"))

我想以递归方式将4分配为每个矩阵元素的长度,然后将它们全部连接起来,以便结果为

# [1] "apples"  "and"     "pears"   NA        "one"     "banana"   
# [6]  NA        NA       "pears"   "oranges" "and"     "pizza"  

这是手动方式。

`length<-`(cb[[1]],4)
# [1] "apples" "and"    "pears"  NA      
`length<-`(cb[[2]],4)
# [1] "one"    "banana" NA       NA      
`length<-`(cb[[3]],4)
# [1] "pears"   "oranges" "and"     "pizza"

我想通过使用递归或编写bquote表达式而不循环来执行此操作。我想我需要使用do.call,但我无法找到正确的方法。我的代码现在是

do.call(`length<-`, list(c(cb, recursive=TRUE), 12))
# [1] "apples"  "and"     "pears"   "one"     "banana"  "pears"    
# [6] "oranges" "and"     "pizza"   NA        NA        NA   

但是这会将NA值附加到连接向量的末尾,我想以递归方式追加它们,因为我可能不知道有多少行(列表元素)cb包含。 recursive =unlist中都有c个参数,可能需要在此处使用。

x替换为当前列表级别的答案(如下所示)将起作用。

replicate(3, quote(`length<-`(cb[[x]], 4L)))
#[[1]]
#`length<-`(cb[[x]], 4L)  # x = 1
#
#[[2]]
#`length<-`(cb[[x]], 4L)  # x = 2
#
#[[3]]
#`length<-`(cb[[x]], 4L)  # x = 3

2 个答案:

答案 0 :(得分:0)

不知道这是不是您要找的,但我试试看:

    eval(parse(text=paste(sep="","c(",paste(sep="","cb[[",1:length(cb),"]][1:4]",collapse=","),")")))

    [1] "apples"  "and"     "pears"   NA        "one"     "banana"  NA       
    [8] NA        "pears"   "oranges" "and"     "pizza"

答案 1 :(得分:0)

这里有两种可能的方法,第一种是flodel(在评论中)非常有效。

resize.recursive <- function(x, len = 4L)
{
    if (!length(x)) NULL
    else c(`length<-`(x[[1]], len), 
           Recall(x[-1, , drop = FALSE], len))
}

resize.recursive(cb)
# [1] "apples"  "and"     "pears"   NA        "one"     "banana"  NA       
# [8] NA        "pears"   "oranges" "and"     "pizza"  

在这个问题上,我在循环中点了一下子弹,然后选择了lapply

replaceLength <- function(x, lev, len = 4L) `length<-`(x[[lev]], len)
unlist(lapply(1:3, replaceLength, x = cb))
# [1] "apples"  "and"     "pears"   NA        "one"    "banana"  NA 
# [8] NA        "pears"   "oranges" "and"     "pizza"  

相同
unlist(lapply(cb, `length<-`, 4L))
# [1] "apples"  "and"     "pears"   NA        "one"     "banana"  NA       
# [8] NA        "pears"   "oranges" "and"     "pizza"  

我仍然愿意接受其他可能性!