A: Naming vector within a for

Asked

Viewed 142 times

3

I’m making a for in my script, but in the last line when I run models$i, I needed that one i was the value of my i of for, would have been able to do?

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)
}
  • 1

    Your code is not reproducible. For example, we do not know what it is x, what packages the commands came out of neuralnet and what is the output of the command bt.run.share. We also don’t know what error appears when the code is executed. I recommend editing the question so that someone who wants to help you can copy and paste your code to run on their own computer.

  • If you want to access column i, the correct ones are models[ ,i]

  • 1

    You probably have to access with [[: models[[i]]

1 answer

1

That object models should be a list. You can find out by doing typeof(models). Even if he is one 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 list elements 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.