很簡單的回圈,生成矩陣x[i,j],然后求x[i,]^2+x[,j]。
為何采用apply比for回圈更慢?
源代碼:
rm(list=ls())
# 生成資料集
x <- cbind(x1=3, x2 = c(10000:1, 1:10000))
# 封裝fun1
fun1<-function(x){
myFUN<- function(x, c1, c2) {
x[c1]^2+x[c2]
}
f1 <- apply(x,1,myFUN,c1='x1',c2='x2')
}
# 封裝fun2
fun2<-function(x){
f2 <- c()
for(i in 1:nrow(x)){
f2[i]<- x[i,1]^2+x[i,2]
}
}
# 封裝fun3
fun3<-function(x){
f3 <- c(x[,1]^2+x[,2])
}
# 分別統計3種方法的CPU耗時。
system.time(fun1(x))
system.time(fun2(x))
system.time(fun3(x))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/245366.html
標籤:其他開發語言
上一篇:Python
下一篇:perl手動安裝make出現問題
