g=integer(5)

for (i in g){

```
g[i]=g[i]+1
```

}

What is wrong with the above code.

I wanted to see g with all 1's but I get g with all zeros

g=integer(5)

for (i in g){

```
g[i]=g[i]+1
```

}

What is wrong with the above code.

I wanted to see g with all 1's but I get g with all zeros

`g=integer(5)`

creates a vector of five zeros. `i`

is then set to zero five times.

You could just do : `rep(1, 5)`

.

First of all, Thank you!

I understand integer(5) creates 5 zeros

But what about the rest of it?

for (i in g){

```
g[i]=g[i]+1
```

}

That should change it zeros to 1's, correct?

Thanks for responding.

The reason for my question is the second part:

for (i in g){

```
g[i]=g[i]+1
```

}

why don't all the g[i] get changed to 1 by the addition equation?

I need the equation to work, but it doesn't.

This seems so simple, and I must be doing something obviously wrong

The first time through it says g[0] = 0 + 1. In R indices equal to 0 are ignored. So nothing changes

Compare these two versions.

```
g=integer(5)
for (i in g){
print(paste("i = ", i))
g[i]=g[i]+1
}
[1] "i = 0"
[1] "i = 0"
[1] "i = 0"
[1] "i = 0"
[1] "i = 0"
g=integer(5)
for (i in seq_along(g)){
print(paste("i = ", i))
g[i]=g[i]+1
}
[1] "i = 1"
[1] "i = 2"
[1] "i = 3"
[1] "i = 4"
[1] "i = 5"
g
[1] 1 1 1 1 1
```

1 Like

Mr. Startz

Thank you!

Mr. FJCC

Thank You!

I think I understand now

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.