转换循环以在构建列表时应用

Convert loop to apply while building list

我正在尝试使用应用函数而不是循环在 R 中构建列表列表,但我无法将工作循环转换为 lapply 格式。请允许我再解释一下情况:

我在 R (getDetails) 中有一个函数,它检索与我传递给该函数的参数相关的详细信息,并在列表中 returns 结果。如果我将一条记录传递给该函数,该函数将运行良好,并且我还构建了一个循环,允许我一次一行地循环遍历数据框,并将数据框的元素逐行传递给我函数依次 returns 列表到列表列表的第 i 个元素 (detailsList[[i]])。我想弄清楚如何将我的 for 循环转换为应用函数。你能帮我吗?我已经创建了一个玩具示例,如果我可以开始工作,将允许我将其推广到我的实际 getDetails 函数。

#use cars dataset for an example
data(cars)
#get number of rows
numrows<-dim(cars)[1]
#initialize empty list
detailsList<-vector("list", numrows)

#This is a toy example of the loop I want to convert to an apply
#I'm having trouble because this builds up a list and returns the results
#to my detailsList one element at a time and I'm not sure how to do this 
#in an apply.
for (i in 1:numrows){
  detailsList[[i]]<-getDetails(cars[i,])
}

detailsList

getDetails<-function(parameters){
   valueA<-parameters[1]+45
   valueB<-parameters[1]+10
   list(valueA, valueB)
}

更新:

我以为我刚刚弄明白了,但似乎当我这样做时,我的列表中出现了第三个维度,所以当我使用它时:

allDetails <- lapply(1:numrows, function(i)  getDetails(cars[i,]))

第一个列表的第二个元素只能用 allDetails[[1]][[1]][2] 访问,而不是像我希望的那样用 allDetails[[1]][2] 访问。有谁知道我在这里做错了什么?

我想我是在@Parfait 的帮助下才弄明白的(谢谢@Parfait!)。如果其他人正在寻找答案,这对我有用,但我欢迎任何其他答案:

lapply(1:numrows, function(i)  getDetails(cars[i,]))

我不得不将我的函数修改为 return 向量而不是列表:

getDetails<-function(parameters){
   valueA<-parameters[1]+45
   valueB<-parameters[1]+10
   c(valueA, valueB)
}

这是用 vapply

编写的循环
out <- vapply(1:nrow(cars), 
              function (i) {
                valA <- .subset2(cars, 1)[i] + 45L
                valB <- .subset2(cars, 1)[i] + 10L
                c(valA, valB)
              }, numeric(2))
t(out) 
#       [,1] [,2]
# [1,]   49   14
# [2,]   49   14
# [3,]   52   17
# [4,]   52   17
# [5,]   53   18
# [6,]   54   19
# [7,]   55   20
# ...
# (returns an array instead of a list, but that can be changed easily).

顺便说一句,我不知道你的最终目标是什么,但就这个例子而言,为什么要 any 循环?

# vectorized
cbind(.subset2(cars, 1) + 45L, .subset2(cars, 1) + 10L)
#      [,1] [,2]
# [1,]   49   14
# [2,]   49   14
# [3,]   52   17
# [4,]   52   17
# [5,]   53   18
# [6,]   54   19
# [7,]   55   20
# ...
# or similar result with
# getDetails(cars) (version with c())