[英]How to make an infinitely recursive list in R: confuse [ and [[
Edit: this question is silly, I confused [ and [[ (thanks @josilber), but I can't delete it. 编辑:这个问题很愚蠢,我混淆了[和[[(感谢@josilber),但是我无法删除它。
How can one make an infinitely recursive list, L == L[1], in R ? 如何在R中制作一个无限递归列表L == L [1]?
A terrible way (for an R novice) is to look at dataset fmri
in package astsa : 对于R新手来说,一个糟糕的方法是查看fmri
软件包中的数据集fmri :
data( fmri, package="astsa" ) # a list with fmri[1] == fmri[1][1] ... ??
print_recursive = function( x ){ # x x[1] x[1][1] ... while list
for( j in 1:5 ){
cat( class(x), len(x), names(x), "\n" )
str(x)
cat( "\n" )
x = x[1] # <-- wrong, should be x[[1]]
if( class(x) != "list" ) break
}
x
}
x = print_recursive( fmri )
The answer to "How can one make an infinitely recursive list, L == L[1], in R" is that it is impossible, because you would need an infinite amount of memory to store a list of infinite recursive depth. 对“如何在R中创建一个无限递归列表L == L [1]”的答案是不可能的,因为您将需要无限数量的内存来存储无限递归深度的列表。
That being said, you can build a recursive list of a specified depth with a simple for loop, at each iteration creating a new list that stores the old list as one of its elements: 话虽如此,您可以使用一个简单的for循环来构建指定深度的递归列表,在每次迭代时创建一个新列表,该列表将旧列表存储为其元素之一:
l <- list()
depth <- 50
for (k in seq(depth-1)) {
l <- list(l)
}
You could write a recursive function to check the depth of a recursive list: 您可以编写一个递归函数来检查递归列表的深度:
recursive.depth <- function(l) {
if (!is.list(l)) 0
else if (length(l) == 0) 1
else 1+max(sapply(l, recursive.depth))
}
recursive.depth(l)
# [1] 50
recursive.depth(fmri)
# [1] 1
Getting back to the example from the question, the list you have is actually not recursive at all (it's just a list of matrices). 回到问题的示例,您拥有的列表实际上根本不是递归的(它只是矩阵列表)。 The reason you think it is recursive is that indexing l[1]
subsets the list (aka it returns the list with just its first element). 您认为它是递归的原因是索引l[1]
是列表的子集(也就是它只返回列表的第一个元素)。 For instance, consider the following very simple list: 例如,考虑以下非常简单的列表:
(l <- list(2))
# [[1]]
# [1] 2
No matter how many times I subset with the [
notation, I will get back the exact same list: 无论我用[
表示法]进行了多少次子集设置,我都会得到完全相同的列表:
l[1]
# [[1]]
# [1] 2
l[1][1]
# [[1]]
# [1] 2
Running this list l
through your print_recursive
function will also result in an infinite loop. 通过print_recursive
函数运行此列表l
也将导致无限循环。 If you wanted to actually extract the first element of the list instead of subsetting the list itself, you should use the [[
notation (eg l[[1]]
). 如果要实际提取列表的第一个元素,而不是子集列表本身,则应使用[[
表示法(例如l[[1]]
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.