How to get a vector to work as an argument in my function in r?

Viewed 46

I am trying to get my function (in r) to work with a two-element vector as an argument, but when I run the function with inputs, one of the elements is "not found".

I've tried using a placeholder as the argument and defining the placeholder later in the function. I've also tried to use concatenated values directly as the argument.

mse.func <- function(ya.vctr, N=gmp$pop, Y=gmp$pcgmp){
    ya.vctr <- c(y, a)
    mean.sq.er <- mean((Y - (y * (N^a)))^2)
    return(mean.sq.er)
}

mse.func(c(5000, 0.10))

I'm expecting a numerical value but mse.func(c(5000, 0.10)) returns an error stating that "object 'y' is not found".

1 Answers

This should work:

mse.func <- function(ya.vctr, N=gmp$pop, Y=gmp$pcgmp){
    mean.sq.er <- mean((Y - (ya.vctr[1] * (N^ya.vctr[2])))^2)
    return(mean.sq.er)
}

mse.func(c(5000, 0.10))

Alternatively, a simpler option is (though it does not accept a vector as input, so it does not answer the question):

mse.func <- function(y, a, N=gmp$pop, Y=gmp$pcgmp){
    mean.sq.er <- mean((Y - (y * (N^a)))^2)
    return(mean.sq.er)
}

mse.func(5000, 0.10)
Related