1

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!

Greg
  • 3,054
  • 6
  • 27

1 Answers1

3

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

FlapJack
  • 156
  • 4
  • Thank you this was very helpful! Yes I figured my original way was not necessarily wrong but when I move on to more complex data files I would like to be concise. – Corbin Platamone Jan 11 '22 at 23:58