Question

I am a beginner in R. I have a question on the following code.

f <- function(x,y){
  x+y[1]+y[2]
}

y <- matrix(1:8, ncol=2);y
x <- 1:4
i <- 1:4
v1 <- f(x[i], y[i,])
v2 <- NULL; v2[i] <- f(x[i], y[i,])
v3 <- NULL; for(i in 1:4){v3[i] <- f(x[i], y[i,])}
v1; v2; v3

The results are the same for v1 and v2. And v3 is what I want. But why can't I just use commands for v1 or v2? Why are they different? Is there any way to modify v1 or v2 a little bit to get the desired results? Thanks a lot in advance!

Was it helpful?

Solution

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

OTHER TIPS

The problem comes from your implementation of f. The way the matrix subsetting works means you are returning the same matrix and always choosing the first two elements for each value in x.

If you write it in a more vectorised way it will work as you intend:

f2 <- function(x,y) x+y[,1]+y[,2]
f2(x,y)
[1]  7 10 13 16
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top