2014-06-26 35 views
1

我有一个列表的列表,用含3个值中的每个子列表。我的目标是以一种系统的方式遍历这个嵌套列表的每个值(即从列表1开始,遍历所有3个值,到列表2等等),对每个列表应用一个函数。但是我的函数碰到了缺失的值和断点,我将这个问题追溯到索引本身,这并不像我期望的那样行事。该列表构造为:索引通过使用嵌套列表的值mapply

pop <- 1:100 
treat.temp <- NULL 
treat <- NULL 

## Generate 5 samples of pop 
for (i in 1:5){ 
    treat.temp <- sample(pop, 3) 
    treat[[i]] <- treat.temp 
} 

## Create a list with which to index mapply 
iterations <- (1:5) 

说明性功能和结果。

test.function <- function(j, k){ 
    for (n in 1:3){ 
    print(k[[n]][j]) 
    } 
} 

results <- mapply(test.function, iterations, treat) 

[1] 61 
[1] 63 
[1] 73 
[1] NA 
[1] NA 
[1] NA 
[1] NA 
[1] NA 
<snipped> 

对于通过'j'的第一个循环,这是有效的。但在此之后它会抛出NAs。但是如果我手动执行它,它会返回我期望的值。

> print(treat[[1]][1]) 
[1] 61 
> print(treat[[1]][2]) 
[1] 63 
> print(treat[[1]][3]) 
[1] 73 
> print(treat[[2]][1]) 
[1] 59 
> print(treat[[2]][2]) 
[1] 6 
> print(treat[[2]][3]) 
[1] 75 
<snipped> 

我敢肯定,这是一个基本的问题,但我似乎无法找到合适的搜索条件,这里或谷歌上找到答案。提前致谢!

编辑为添加: MrFlick的回答对我的问题很好。我在我的实际使用中有多个列表输入(因此为mapply)。一个更详细的例子,几个笔记。

pop <- 1:100 
years <- seq.int(2000, 2014, 1) 

treat.temp <- NULL 
treat <- NULL 
year.temp <- NULL 
year <- NULL 

## Generate 5 samples of treated states, control states and treatment years 
for (i in 1:5){ 
    treat.temp <- sample(pop, 20) 
    treat[[i]] <- treat.temp 

    year.temp <- sample(years, 1) 
    year[[i]] <- year.temp 
} 

## Create a list with which to index mapply 
iterations <- (1:5) 

## Define function 
test.function <- function(j, k, l){ 
    for (n in 1:3){ 

    ## Cycles treat through each value of jXn 
    print(k[n]) 
    ## Holds treat (k) fixed for each 3 cycle set of n (using first value in each treat sub-list); cycles through sub-lists as j changes 
    print(k[1]) 
    ## Same as above, but with 2nd value in each sub-list of treat 
    print(k[2]) 
    ## Holds year (l) fixed for each 3 cycle set of n, cycling through values of year each time j changes 
    print(l[1]) 
    ## Functionally equivalent to 
    print(l) 
    } 
} 

results <- mapply(test.function, iterations, treat, year) 
+0

你的示例建立是向量的列表,在这种情况下,它似乎简单的使用'lapply'一些功能适用于每一个值在每个载体 - 如,'lapply(享受,函数(X)X/2 )'如果你只是想把所有的东西都分成两份。你能否澄清你的问题? – aosmith

+0

我认为你是对的(正如MrFlick下)关于lapply在我的例子。我为后人增加了一个更详细的例子。我使用了mapply,因为我有多个输入列表,有些需要用j循环,但在n的所有迭代中保持固定,而另一些需要循环j和n。有可能lapply可以处理,我只是不知道如何。 – Amberopolis

回答

2

那么,你可能会误解mapply如何工作。该函数将循环通过作为参数传递的两个迭代,这意味着treat也将是每次迭代的子集。从本质上讲,被调用的函数是

test.function(iterations[1], treat[[1]]) 
test.function(iterations[2], treat[[2]]) 
test.function(iterations[3], treat[[3]]) 
... 

你好像对待k变量就好像它是整个列表。另外,你的索引也会倒退。但只是为了让你的测试工作,你可以做

test.function <- function(j, k){ 
    for (n in 1:3) print(k[n]) 
} 

results <- mapply(test.function, iterations, treat) 

但这并不是真正的超级真棒方式迭代列表。你究竟想要完成什么?

+0

你能解释为什么用这种方法迭代列表是不理想的吗? –

+0

如果你只是想要这些值的顺序,你可以做'unlist(treat)'。这样做没有任何超级错误,它似乎可能更容易对列表本身的“lapply”或东西。这取决于你在做什么,我猜的值。 – MrFlick