Reputation: 1
Apologies for the dumb question, but I've just begun teaching myself programming and working with R and have been stuck on this question for a couple of days. I'm creating a vector that has three elements to it and then trying to write a for loop that adds one to each element. This is what I have so far.
```{r}
vec <- c(3, 1, 4)
for (j in 1:dim(vec)[1]
vec = vec + 1
}
I tried looking at some examples and this was the closest I got, and I feel like it should work, but I keep getting errors. Any help would be greatly appreciated.
Upvotes: 0
Views: 9420
Reputation: 329
R has vector aware functions. Most classic math operations are 'vectorized' .
The other trick is that some vectorized functions features recycling.
So when you do
v <- c(1, 2, 4)
v <- v + 1
The number 1 is recycled as a vector that matches the size of v.
Given this, v+1 is the same as
v <- c(1, 2, 4) + c(1, 1, 1)
Note your for loop above has various syntax errors
for (j in 1:dim(vec)[1] vec = vec + 1 }
Should be
for (j in 1:length(vec)) { vec[j] <- vec[j] + 1}
Upvotes: 3
Reputation: 491
R is built around vectors, so functions and arithmetic can be performed on entire vectors. for
loops will be much slower than making use of R's native vector-based operations. Just remove the for
loop and it will work. As Pierre commented, only vec + 1
is needed.
vec <- c(3, 1, 4)
vec <- vec + 1
print(vec)
#[1] 4 2 5
Though you would never do it this way, to fix your loop, do this:
vec <- c(3, 1, 4)
for (j in 1:length(vec)){
vec[j] = vec[j] + 1
}
print(vec)
#[1] 4 2 5
Upvotes: 1