'For Loop in R: Error in y[[j]] : subscript out of bounds
I am trying to calculate a value and insert the result into a results list. Next, I'd like to use the previous result as an input, run calculation using previous result, and insert into new result into the results list.
x = seq(1,10, by = 1)
y = list()
i = 2
j = 1
for(i in 1:10){
y[i] = (x[i] - y[[j]])/2
i = i +1
j = j + 1
}
Solution 1:[1]
Do you mean this ? :
x = seq(1, 10, by = 1)
y = list()
i = 2
j = 1
for(i in 1:10){
y[[i]] = (x[i] - y[[j]])/2
# i = i+1 unnecesary
j = j + 1
}
As others advised this led to error due to uninitialized list.
Now works, but is kinda strange:
x = seq(1, 10, by = 1)
y = list()
i = 2
j = 1
# initialize y with random stuff
for(i in 1:10){
y[[i]] = rnorm(5) # fill with 5 random values
}
for(i in 1:10){
y[[i]] = (x[i] - y[[j]])/2
# i = i+1 unnecesary
j = j + 1
}
Please note that i = 2 is meaningless since its value is overriden by both loop indexes, which are named the same.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
