Skip to content

Getting a vector result from a computed index

2 messages · Justin Long, Ben Tupper

#
Greetings,

I confess to being new to R, which I am exploring for some simulation
modeling purposes. I am a long time programmer in PHP.

I am having some trouble getting over the "steep learning curve" with
some very basic things which are probably just little "a-ha" things in
R. I have hunted and hunted through the manual and cannot figure this
one out, so I am appealing for help.

I have the following program:

results <- replicate(10000,0)

for (year in 2000:2050) {
print(year);
for (i in 1:10000) {
x=results[i];
if (x == 0) {
prev = results[i-1];
next = results[i+1];
prob=0.1;
if (i>=1) {
if (prev==1) { prob=prob+0.4; }
}
if (i<10000) {
if (next==1) { prob=prob+0.4; }
}
y=runif(1,0,1);
if (y<prob) { x=1; }
results[i]=x;
}
}
}

No matter how I try this (and I've tried a number of variations), I
get an error similar to

Error in next = results[i + 1] : invalid (NULL) left side of assignment

I need to be able to loop through the results vector and compare the
previous/next items in the list to the current one. Is that possible?
What am I missing?

Cordially,
Justin Long
#
Hi,
On Mar 22, 2013, at 11:09 PM, Justin Long wrote:

            
I'm not very clear on what you are trying in the above code block, but comparing neighbor values is very easy.

n <- 10
x <- floor(runif(n, min = 1, max = 10))
dx <- diff(x)
[1] 6 3 2 4 8 8 2 2 4 2
[1] -3 -1  2  4  0 -6  0  2 -2

Is that what you are aiming for?

Also, 'next' is a reserved word in R, that might be why an error is raised.  See ?next  

Even if you could get past that, you'll get unexpected results if the index [i-1] falls to less than 1 or the index [i+1] rises to greater than the length of results.
numeric(0)
[1] NA

Cheers,
Ben



Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org