Reputation: 13
Is there a way to use the sum()
function in R to add two non-sequential elements in a vector in R. For example, if vector1 = c(100,200,300,400,500)
and I wanted to add the first (100) and the fifth (500) variable together? I usually just type out vector1[1] + vector1[5]
but idk if this is proper. Thank you!
Upvotes: 1
Views: 59
Reputation: 156
When it comes to programming, there are generally many different ways to do almost everything. For something as simple as adding two vector elements together, there are also many ways to do it.
vector1 <- c(100, 200, 300, 400, 500)
sum(vector1[1], vector1[5])
vector1[1] + vector1[5]
sum(vector1[c(1,5)])
None of these are necessarily better or worse, but as you move on to more complex operations, slight differences can actually have a massive impact. Take this question on reading CSV files for example: https://stackoverflow.com/a/15058684/16299117
Upvotes: 3