【发布时间】:2014-06-26 15:36:32
【问题描述】:
我有一个列表列表,每个子列表包含 3 个值。我的目标是以系统的方式循环遍历这个嵌套列表的每个值(即从列表 1 开始,遍历所有 3 个值,转到列表 2,等等),对每个值应用一个函数。但是我的函数遇到了缺失值和中断,我已经将问题追溯到索引本身,它的行为并不符合我的预期。列表构造如下:
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”的第一个循环,这是有效的。但在那之后它会抛出 NA。但如果我手动执行,它会返回我期望的值。
> 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>
我确定这是一个基本问题,但我似乎无法在此处或 Google 上找到正确的搜索词来找到答案。提前致谢!
已编辑添加: 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)
【问题讨论】:
-
您的示例设置是一个向量列表,在这种情况下,使用
lapply将某些函数应用于每个向量中的每个值似乎很简单——如,lapply(treat, function(x) x/2)如果您只是想要将所有内容除以 2。您能否进一步澄清您的问题? -
我认为你是对的(如下面的 MrFlick)关于 lapply 在我的例子中。我为后代添加了一个更详细的示例。我使用 mapply 是因为我有多个输入列表,有些需要用 j 循环,但在 n 的所有迭代中保持固定,而另一些需要用 j 和 n 循环。有可能 lapply 可以处理,我只是不知道如何。