R用于将回路输出到表中

时间:2018-07-24 17:19:17

标签: r function loops rstudio

这是我的代码的伪装:

parameters$x<-0
parameters$y<-0
for (x in c(1:2)){
  for (y in c(10,20,30,40,50,60,70,80,100)){
control <- rpart.control(minsplit = x,
                         minbucket = round(y),
                         maxdepth = 10,
                         cp = 0)
tune_fit <- rpart(survived~., data = data_train, method = 'class', control = control)

parameters[x] <-accuracy_tune(tune_fit)
}}

我基本上想要一个具有x行和y列的表(基于我的xy输入在for循环中),然后存储该函数的输出作为此新表中的值。我知道我要使用参数执行的操作不起作用。

1 个答案:

答案 0 :(得分:0)

使用此解决方案,accuracy_tune返回的任何结果都将存储在矩阵中。虽然,您没有提供太多信息,但这是我的解决方案:

# create matrix to store output
parameters <- matrix(data=NA, nrows=2, ncols=10)

# value to use for iteration
x_vals <- c(1:2))
y_vals <- c(10,20,30,40,50,60,70,80,100))

# iterate over values
for (x in seq(x_vals){
  for (y in seq(y_vals){
control <- rpart.control(minsplit = x,
                         minbucket = round(y),
                         maxdepth = 10,
                         cp = 0)
tune_fit <- rpart(survived~., data = data_train, method = 'class', control = control)

parameters[x,y] <-accuracy_tune(tune_fit)
}}

# set row and column names
colnames(parameters) <- y_vals
row.names(parameters) <- x_vals