The problem here is that your function f
doesn't vectorize in the second argument. You can see what is happening if you explicitly evaluate the addends inside the function:
> x[i]
[1] 1 2 3 4
> y[i,][1]
[1] 1
> y[i,][2]
[1] 2
So you can see, f(x[i],y[i,])
is the same as evaluating 1:4 + 1 + 2
:
> 1:4 + 1 + 2
[1] 4 5 6 7
> f(x[i],y[i,])
[1] 4 5 6 7
If you are expecting a matrix in the second argument, you can write a vectorized version of the function, as described by @James. Another option is to cast y
as a data frame:
> f(x,data.frame(y))
X1
1 7
2 10
3 13
4 16
The reason this works is that a data frame is represented as a list of columns, while a matrix is represented as an array with a dimension attribute. So y[1]
will give you the first element of y
whereas data.frame(y)[1]
will give you the first column:
> y[1]
[1] 1
> data.frame(y)[1]
X1
1 1
2 2
3 3
4 4