Home > OS >  Results differ between printed output and stored vector in nested for loop. What gives?
Results differ between printed output and stored vector in nested for loop. What gives?

Time:10-19

I believe this may be straightforward, but I have been trying to figure this out for hours. The printed output is how I would like my vector. It is doing exactly what I want.

x1<-c(1,2,3,4)
x2<-c(1,0)
len<- length(filename)
output <- vector("numeric", 8)

for (i in x1){
    for(j in x2){
       print(sum(i j))
       output[i]<- i
    }
}
output

But, I am confused as to why I get these two different results:

[1] 2
[1] 1
[1] 3
[1] 2
[1] 4
[1] 3
[1] 5
[1] 4
> output
[1] 1 2 3 4 0 0 0 0

How do I store the print results as a vector? Thanks.

CodePudding user response:

According to ?print

print prints its argument and returns it invisibly (via invisible(x)).

We may need to initialize an object (sum1) and start concatenating the output from sum(i j) to the object while updating the output from each iteration back to 'sum1'

sum1 <- NULL
 output <- vector("numeric", 8)

 for (i in x1){
     for(j in x2){
      sum1 <- c(sum1, i   j)
  output[i]<- i
  }
 }

-output

> sum1
[1] 2 1 3 2 4 3 5 4

Regarding the difference between the print and 'output'. It is obvious - printing is done on the sum(i j) (sum is redundant here as i j does the sum as well) where as output is stored with the i value alone. Also the initialization of vector is a numeric vector with value 0 of length 8

>  output <- vector("numeric", 8)
> output
[1] 0 0 0 0 0 0 0 0

Initialization can also be done as

> output <- numeric(8)

where as the x1 values are of length 4. Thus, after the first 4 iteration, there is nothing to fill the 0 value remains as such.


In R, this can also be done with outer

> c(t(outer(x1, x2, FUN = ` `)))
[1] 2 1 3 2 4 3 5 4

Or with sapply

> c(sapply(x1, ` `, x2))
[1] 2 1 3 2 4 3 5 4
  • Related