0

I am creating a function to use in gridSearch:

Negs <- c() 
Poss <- c()
Fun <- function(x){
for(i in 1:200){
    j <- a[i]
    k <- b[i]
    l <- c[i]
    m <- d[i]
    Negs[i] <- x[1L]*j + x[2L]*k + x[3L]*l + x[4L]*m
}
for(i in 1:200){
    n <- e[i]
    o <- f[i]
    p <- g[i]
    q <- h[i]
    Poss[i] <- x[1L]*n + x[2L]*o + x[3L]*p + x[4L]*q
}
print(length(Poss[Poss<=max(Negs)]))}

I then use gridSearch with this function and it works fine.

It would be useful to have the vectors Negs and Poss populated; however, this does not seem to happen. On my global environment they are empty.

Then trying (just to try and work out what is going on):

Results <- function(x){
for(i in 1:200){
    j <- a[i]
    k <- b[i]
    l <- c[i]
    m <- d[i]
    Negs[i] <- x[1L]*j + x[2L]*k + x[3L]*l + x[4L]*m
    cat()
}
for(i in 1:200){
    n <- e[i]
    o <- f[i]
    p <- g[i]
    q <- h[i]
    Poss[i] <- x[1L]*n + x[2L]*o + x[3L]*p + x[4L]*q
}
print(Negs)
print(Poss)
}

Results(c(2,1,2,1))

This works and prints Negs and Poss, but again they are not stored in the global environment.

What am I missing?

Thanks for the help!

  • 3
    "What am I missing?" -- your question is missing a [mcve]. See [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269/4996248) for what this would mean in R. – John Coleman Apr 30 '21 at 16:14
  • 4
    In any event, it is poor practice to try to mutate the global environment though function side effects. If you *really* want to do that, you could use things like `Poss[i] <<- x[1L]*n + x[2L]*o + x[3L]*p + x[4L]*q` rather than `Poss[i] <- x[1L]*n + x[2L]*o + x[3L]*p + x[4L]*q` -- but it really isn't good practice. Why not *return* what you want from the function? – John Coleman Apr 30 '21 at 16:22
  • 2
    BTW, you really don't need that for loop. R works with vectors. Just do `Negs <- x[1] * a+ x[2] * b + x[3] * c + x[4] * d`. – dash2 Apr 30 '21 at 16:26
  • As @JohnColeman wrote, you should usually avoid making changes to the global environment within function calls. You can simply assign your results to a desired object, with `object<-Results()` – GuedesBF Apr 30 '21 at 16:58
  • 1
    It seems like this may be what you are looking for: https://stackoverflow.com/questions/1826519/how-to-assign-from-a-function-which-returns-more-than-one-value –  Apr 30 '21 at 17:01

0 Answers0