Rather than using a for loop, I would use one of the functions designed to iterate over a list or matrix. Below are two solutions, one using the apply function from base R and the other using one of the map functions from the purrr package. In the apply function, setting MARGIN to 2 means the function is applied over the columns.
df <- data.frame(V1 = seq(1,15), V2 = seq(2,16), V3 = seq(3,17))
df
#> V1 V2 V3
#> 1 1 2 3
#> 2 2 3 4
#> 3 3 4 5
#> 4 4 5 6
#> 5 5 6 7
#> 6 6 7 8
#> 7 7 8 9
#> 8 8 9 10
#> 9 9 10 11
#> 10 10 11 12
#> 11 11 12 13
#> 12 12 13 14
#> 13 13 14 15
#> 14 14 15 16
#> 15 15 16 17
#Define function to add first 10 elements
Sum10 <- function(x) {
sum(x[1:10])
}
#with apply()
SUMS <- apply(df, MARGIN = 2, FUN = Sum10)
SUMS
#> V1 V2 V3
#> 55 65 75
#With map_dbl() function
library(purrr)
SUMS2 <- map_dbl(df, Sum10)
SUMS2
#> V1 V2 V3
#> 55 65 75
Created on 2019-04-26 by the reprex package (v0.2.1)