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