Sarah N. Aidirishka
Sarah N. Aidirishka

Reputation: 11

How to create a function within function

I have a problem in creating my function to impute my generated missing values. I have a generating data function, generating missing values function and imputing missing values function. But how can I combine them into one function?

# generate data
data <- function (n,alpha,kappa,miu){
    X = rvm(n,alpha,kappa)
    delta = rvm(n, 0, kappa)
    epsilon = rvm(n, 0, kappa)
    x = (X + delta)%%(2*pi)
    Y = (alpha + X)%%(2*pi)
    y = (Y + epsilon)%%(2*pi)
    sample = cbind(x,y)
    return(sample)
    }

#generate missing values
misVal <- ampute(data=data(10,0.7854,5,0),prop=0.25,bycases=FALSE)

#impute missing values
impData <- mice(misVal,m=5,maxit=50,meth='pmm',seed=500)
summary(impData)

Upvotes: 1

Views: 47

Answers (1)

EChisholm
EChisholm

Reputation: 11

Combine all three functions into one large custom function...

nameYourFunction <- function(n,alpha,kappa,miu){

X = rvm(n,alpha,kappa)

delta = rvm(n, 0, kappa)

epsilon = rvm(n, 0, kappa)

x = (X + delta)%%(2*pi)

Y = (alpha + X)%%(2*pi)

y = (Y + epsilon)%%(2*pi)

sample = cbind(x,y)

#generate missing values

misVal <- ampute(data=sample,prop=0.25,bycases=FALSE)

#impute missing values

impData <- mice(misVal,m=5,maxit=50,meth='pmm',seed=500)

return(impData)
}

Then to run...

final_data <- nameYourFunction(n = 10, alpha = 0.7854, kappa = 5, miu = 0)
summary(final_data)

Obviously you may want to rename the function based on your own preferences. If you wanted something more flexible, like to be able to easily supply arguments for the other function called within nameYourFunction, then you would add them to the list of arguments provided in the first line of code. So it might end up looking more like...

nameYourFunction <- function(n,alpha,kappa,miu,prop,m,maxit,meth,seed){...} Then supplying those values to the function call like...

final_data <- nameYourFunction(n = 10, alpha = 0.7854, kappa = 5, miu = 0, prop = 0.25, m = 5, maxit = 50, meth = 'pmm', seed = 500)

And removing the hard coded values from within the custom function. I would probably recommend against this though as that is a lot of arguments to keep track of!

Upvotes: 1

Related Questions