R: Name vector within a for

3

I'm doing a for in my script, but in the last line when I run models$i , I needed that i to be the value of my i of for , how would I do it?

for(i in x){
    maxit <- as.integer(1000000)
    algoritmo <- neuralnet(dados2016[,5] ~ dados2016[,4],
    data <- dados2016, hidden=i ,threshold=1, stepmax=maxit)
    teste <- compute(algoritmo, dados2017[,4])

    precos$weight[] <- NA
    precos$weight[] <- if(dados2017[,4] < teste$net.result[,1], 1, 0)
    models$i <- bt.run.share(precos, clean.signal=T)
}
    
asked by anonymous 31.01.2017 / 01:07

1 answer

1

This models object must be a list. You can find out by doing typeof(models) . Even though it is a data.frame , it will also be a list (Example: typeof(mtcars) ).

If the object is a list, you can access the elements using the $ operator. But this does not accept strings as inputs. Example:

x <- "cyl"
mtcars$x

One way to access elements of a list by name is to use the [[]] construct. With this you can use:

mtcars[[x]]

The same thing can be done to change objects in a for.

for(i in colnames(mtcars)){
  mtcars[[i]] <- mtcars[[i]]/2
}
mtcars
    
01.02.2017 / 18:47