我已经看过这个示例来说明如何用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))
答案 0 :(得分:0)
在循环myData[myData$Country == ii & myData$Year == jj, c("computedFigure")] <- myFunction(tempX, tempY)
的最后一行中,函数myFunction
被应用并记录在computedFigure
列中。
variable1和variable2随机设置以说明myFunction
中myData(x和y)中的数据。
for循环正在探索国家和年份中的组合...
这两个代码(for loop和lappy)将不会产生完全相同的结果。 lapply将仅使用myFunction
的结果生成一个列表。 for循环将生成一个数据帧。
答案 1 :(得分:0)
实际上,您不需要嵌套的*apply
函数,实际上可以使用outer
+ diag
来计算computedFigure
,这可以达到与通过嵌套的for
循环。
myData$computedFigure <- diag(with(myData,outer(variable1,variable2,myFunction)))