索引R中的嵌套列表

时间:2013-07-13 22:34:49

标签: r

我有一个嵌套列表:

>str(myNestedList)
List of 9
$ : num [1:33, 1:4] 42.84 36.49 12.17 27.64 4.33 ...
$ : num [1, 1:4] 61 NA NA NA
$ : num [1:27, 1:4] 6.63 NA NA NA 1.75 ...
$ : num [1:17, 1:4] 63.6 135.2 NA 31.9 NA ...
$ : num [1:5, 1:4] NA 19.6 42.4 22.3 41.7 ...
$ : num [1:45, 1:4] NA 20.3 12.1 78.4 343.9 ...
$ : num [1:13, 1:4] 47.1 14.3 130.6 12.2 28.2 ...
$ : num [1, 1:4] 315 NA NA NA
$ : num [1:65, 1:4] 21.16 5.31 13.1 3.23 25.77 ...

我想使用最后一个维度索引嵌套列表,如下所示:

myOuputList <- list()
for(i in 1:4) {
  myOutputList[[i]] <- myFunction(myNestedList[[,]][,i])
}

请一位善良的人解释为什么这不起作用以及如何解决它?

干杯,

2 个答案:

答案 0 :(得分:6)

列表将使用[[和带有[,]索引的矩阵(不是列表)提取,但您需要为函数提供一些工作。 (目前你不是。)所以,如果你想要4h矩阵和i,j值为10和3,这将提供这个值:

 myNestedList[[4]][10,3]

评估从左到右进行。包含在一个函数中并从上下文中假设您只需要第i列(由于i通常引用行,这有点令人困惑):

 pull.ith.col.from.nth.mat <- function(lis, n, i) lis[[n]][ , i]

答案 1 :(得分:2)

R肯定有一些愚蠢的语法,重申其他人的说法:

 a<-list()        #instantiates a 
 a[[1]]<-list()   #instantiates the first row of a 
 a[[1]][1]<-'col1'#puts values in the first row 
 a[[1]][2]<-'col2'
 a[[1]][3]<-'col3'
 a[[2]]<-list()   #Each row requires independent instantiation (if that's a word)
 a[[2]][1]<-'val1'
 a[[2]][2]<-'val2'
 a[[2]][3]<-'val3'
 print(a)

此模式扩展到更高维度的列表,

a <- list()
a[[1]]<-list()
a[[1]][[1]]<-list()          # When Assigning lists() to a location use [[]]
a[[1]][[1]][[1]]<-c(1,2,3)   # When Assigning vectors to a location use [[]]
a[[1]][[1]][2]<-7.2# some times you can get away with [] but sticking with [[]]
a[[1]][[1]]['key']<-'value'                         # seems to be the safe bet.
print(a)

'$'和[]可用于访问特定索引的列表,但必须用[]指定整数索引,这可能是安全的选择。

a <- list()
a[[1]] <- 'one'
a[['key']] <- 'value'
print (paste('a[1]  ::',a[1]))
print (paste('a[[1]]::',a[[1]]))
print (paste('a["key"]  ::',a["key"]))
print (paste('a$key::',a$key))# a$1 would cause an error with int indices
print (paste('a[["key"]]::',a[["key"]]))

双括号感觉不必要,如果list()表现得更像python {}词典,但是一旦你习惯了[[]]就会非常相似。() 你可以选择自己的立场来在R中做同样的事情的各种方式,因为最近只是来到它的人我发现它通常很难阅读,但它是相当的语言和麻烦可能是值得的。 请享用, 〜