我曾经在C ++中工作,我认为我误解了for循环(或迭代)在R中是如何工作的。我想在for循环中更改列表项,但for循环似乎是一个临时副本而只是改变它?我怎么能阻止这个?这似乎是一个微不足道的初学者问题,但我无法在stackoverflow上找到关于为什么会发生这种情况的教程/问题。
码:
myList <- list(a=1, b=1, c=1, d=1)
for(item in myList){item <- 3}
myList
# Expected output: 3,3,3,3 - Real output: 1,1,1,1
# Additionally, I now have a variable "item" with value 3.
for(item in myList)
创建了一个名为item
的新对象
如果你想引用列表中的项目,最好通过调用myList[1]
的位置或myList[["a"]]
的名字来实现。
您可以使用索引循环遍历列表(作为建议的注释之一)。
myList <- list(a=1, b=2, c=4, d=5)
for(i in 1:length(myList)){
myList[i] <- 3
}
myList
但我会推荐一种矢量方法。看一下这个:
myList <- list(a=1, b=2, c=1, d=5)
myList=='1'
myList[myList=='1']=3
myList
myList[names(myList)=='a']=9
myList
现在你没有任何冗余变量。
这实际上是R中推荐的方法。For循环计算量太大。
正如@nicola所说,lapply
应该是一个不错的选择。以下是基于您的问题的示例。
myList <- list(a = 1, b = 1, c = 1, d = 1) # output: 1,1,1,1
lapply(myList, function(x) 3) # output: 3,3,3,3
# lapply iterates over every list item