A few things I noticed:
- Make sure you run the function (you've declared it here, but you haven't run it)
- You're saving over the variable y each time the loop runs. In this case, your output will be the sum of the last two rows (I don't think this is what you want).
- x is a vector, not a dataframe, as you've selected only the first column. As such, x[i,1] will produce an error, because x is one-dimensional. x[i] is what you want.
Here's how you can do it:
x <- airquality[ , 1]
# Declare your function
fun <- function(x){
y <- numeric()
for (i in 1:(length(x)-1)){
y <- c(y, sum(x[i], x[i+1])) # Add to y with each loop cycle
}
y
}
# Run your function:
fun(x)
Note: there are more efficient ways to do this in R, but it looks like you might be more comfortable with C++ style looping. But done is better than perfect, I guess.
edit: formatting