Re: [問題] for loop 結果

作者: celestialgod (天)   2015-03-01 08:58:20
: [軟體熟悉度]:
: 入門(寫過其他程式,只是對語法不熟悉)
: [問題敘述]:
: 需要做四個for loop 想將結果儲存成以下形式
: degree scale offset C error
: 1 1 1 1 0.005
: 1 1 1 2 0.006
: . .. ...
:
: [程式範例]:
: cross2 <- data.frame(degree=numeric(),
: scale=numeric(),
: offset=numeric(),
: C=numeric(),
: cross=numeric())
: for (i in 1:3){
: for (j in 1:3){
: for (k in 1:7){
: for (l in 1:5){
: Csvc.poly <- ksvm(training1[,13]~.,data=Train.subset,type="C-svc",
: kernel="polydot",
: kpar=list(degree=degree[i],
: scale=scale[j],offset=offset[k]),C=C[l],cross=10)
: cross2<-cbind(degree,scale,offset,C,cross=cross(Csvc.poly))
: }
: }
: }
: }
: 用了cbind 但結果不正確
: 想請問有沒有建議使用的指令能得到上述的結果
: 謝謝
:
因為你是用迴圈 所以應該是每次回圈存一個row...
cross2 = matrix(NA, 3*3*7*5, 5)
m = 1
for (i in 1:3){
for (j in 1:3){
for (k in 1:7){
for (l in 1:5){
Csvc.poly <- ksvm(training1[,13]~.,data=Train.subset,type="C-svc",
kernel="polydot",
kpar=list(degree=degree[i],
scale=scale[j],offset=offset[k]),
C=C[l],
cross=10)
cross2[m,] <- c(degree[i], scale[j], offset[k] ,C[l],
cross(Csvc.poly))
m = m + 1
}
}
}
}
cross2 = data.frame(cross2)
names(cross2) = c("degree", "scale", "offset", "C", "cross")
這樣的case,我會建議下面的作法
input = expand.grid(degree, scale, offset, C)
cross = mapply(function(d, s, o ,C) {
cross(ksvm(training1[,13]~.,data=Train.subset,type="C-svc",
kernel="polydot", kpar=list(degree=d, scale=s,offset=o),
C=C,cross=10))
}, input[,1], input[,2], input[,3], input[,4])
cross2 = data.frame(input, cross)
names(cross2) = c("degree", "scale", "offset", "C", "cross")
或是利用plyr做
library(plyr)
input = expand.grid(degree = degree, scale = scale,
offset = offset, C = C)
cross2 = mdply(input, function(degree, scale, offset ,C) {
cross(ksvm(training1[,13]~.,data=Train.subset,type="C-svc",
kernel="polydot", kpar=list(degree=degree,
scale=scale,offset=offset), C=C, cross=10))})

Links booklink

Contact Us: admin [ a t ] ucptt.com