【发布时间】:2020-06-03 18:08:18
【问题描述】:
我发送了这个例子来解释如何用 lapply() 函数替换嵌套的 for 循环。但是我不完全理解嵌套 for 循环中发生了什么?
根据我的理解,for 循环为所有年份的每个国家/地区创建了两个新变量tempX 和tempY,但是在 for 循环中参数的最后一行发生了什么?
variable1 和 variable2 的用途是什么?
# Generate random data:
allCountries <- LETTERS[1:10]
allYears <- 1990:2012
myData <- expand.grid(allCountries, allYears) # create a dataframe with all possible combinations
colnames(myData) <- c("Country", "Year")
myData$variable1 <- rnorm(nrow(myData))
myData$variable2 <- rnorm(nrow(myData))
# Silly function to perform
myFunction <- function(x, y){
x * y - x / y
}
### Doubly-nested loop ###
myData$computedFigure <- NA # Make an "empty" variable in my data.frame
for(ii in allCountries){
for(jj in allYears){
tempX <- myData[myData$Country == ii & myData$Year == jj, c("variable1")]
tempY <- myData[myData$Country == ii & myData$Year == jj, c("variable2")]
# "Save" results into appropriate location in my data.frame
myData[myData$Country == ii & myData$Year == jj, c("computedFigure")] <- myFunction(tempX, tempY)
}
}
### Simple lapply() approach ###
computedFigureList <- lapply(1:nrow(myData), function(x){
tempX <- myData[x, c("variable1")]
tempY <- myData[x, c("variable2")]
# "Save" results into appropriate location in my data.frame
myFunction(tempX, tempY)
})
myData$computedFigure2 <- unlist(computedFigureList)
with(myData, plot(computedFigure, computedFigure2))
【问题讨论】:
-
variable1和variable2只是数据。可能是 GDP($) 和 MedianIncome($)。或者您可能对其进行数学运算的任何其他变量。它们只是组成的数据。 -
for 循环的最后一行在数据框中定位您要放置结果的位置
myData[...,...],然后将数学结果放在那里myFunction(tempX,tempY。 -
不要使用
lapply和匿名函数,你可以只使用myData$computedFigure <- mapply(myFunction, myData$variable1, myData$variable2)
标签: r function for-loop apply lapply