Eliseo Di Folco
Eliseo Di Folco

Reputation: 151

R function - Error argument is missing, with no default

I am testing a simple function in R that should transform a time series object into a data frame. However the code works fine outside the function but within the function it gives me the error in the object.

>fx<-function(AMts) {
  x<-as.data.frame(AMts)
  return(x)
}
>fx()

I expeced to have the data.frame x in my environment, but I got Error in as.data.frame(AMts) : argument "AMts" is missing, with no default

Upvotes: 1

Views: 11133

Answers (1)

datajoel
datajoel

Reputation: 100

If it's inside a function, you need to have "<<-" as the assignment operator instead of the traditional "<-". <<- tells R to keep the object after the function is done running.

>fx<-function(AMts) {
  x<<-as.data.frame(AMts) # "<<-" is what saves "x" in your environment
  return(x) # remove this line; this prints data frame "x" to the console, but it doesn't save it
}
>fx(AMts)

EDIT: As the commenters have already pointed out, you aren't including any parameters in your function. Above I made it fx(AMts) to make it clear you need to pass in AMts to the function too.

Upvotes: 2

Related Questions