Reputation: 6741
Suppose I have a vector:
my.vector <- rep(0, length.out = 100)
I want to modify each element of the vector by a new value depending on the element index.
Of course, I can use a for loop:
for(i in 1:length(my.vector)) {
my.vector[[i]] <- my.vector[[i]] + i * 0.25
}
But I'm sure there are better ways to do this in R.
With sapply
?
sapply(seq_along(my.vector), function(i) my.vector[[i]] + i * 0.25)
OK, I get the same result, but it's less readable. Do you know of other cleaner ways?
Upvotes: 0
Views: 54
Reputation: 38500
There are a large number of ways to approach this. One of the canonical methods uses seq
:
myVectorSeq <- my.vector + seq(.25, 25, length.out=length(my.vector))
You can accomplish @lorenzo-rossi's method using seq_len
:
myVectorSeq <- my.vector + (seq_len(length(my.vector)) * .25)
seq_len
, which is faster than the more flexible seq
function.
Upvotes: 1
Reputation: 1481
Simply create a new vector and then use a vectorized sum:
sums_vec = (1:length(my.vector)) * 0.25
my.vector + sums_vec
Upvotes: 1