Working with sums in R

How to work with amounts in R? I can't seem to find an easy way to calculate the sums \ sum_ {i = m} ^ n a_i. There are three things here; where does the summation start, where it ends, and which elements should be summed up.

I have a df dataframe and I would like to compute sum_ {i = 1} ^ {n-3} df $ col [i] * df $ col [i + 3], col is a column 1000 in df long, i.e. e. n = 1000 ... How can I do this? I found one very cumbersome way to do this, namely

new = NULL

for (n in 1:997)
{ new = df$col[n]*df$col[n+3] }

sum(new)

      

This is a silly way to do it, since it happens in a more "natural" way? Yes, I'm sure this exact question has been asked, but I didn't know how to narrow my searches. "R + sum + why programmers don't think like mathematicians" maybe;) Anyway, hints or links to tutorials for R beginners would be greatly appreciated, thanks.

+3


source to share


3 answers


You can do it with

sum(df$col[1:997] * df$col[4:1000])

      



It will be much faster than index scrolling and individual multiplication.

+6


source


You are better off using vectorization and some tricks to avoid indices:



with(df, sum(head(col,-3)*tail(col,-3)))

      

+3


source


Or use a function lead

:

sum(df$col * lead(df$col, 3, default = 0))

      

0


source







All Articles