R list parts of a function

I have a large function I use to assign variable types to columns in a data frame.

setVarType <- function(x){
    x$Species <- as.factor(as.character(x$Species))
    x$Sepal.Length <- as.numeric(as.character(x$Sepal.Length))
    return(x)
}

df1 <- setVarType(df1)

I just created a new version of the data frame and the function is breaking because some of the column names are missing in the new data set. Is there a way to see the structure of a function and extract the required variable names into a vector so I can do something like:

setdiff(functionVariables, dataFrameVariables)

Answers


I think this is what you're looking for:

getLValueDollarRHS <- function(pt) do.call(c,lapply(as.list(pt),function(pte) if (is.call(pte)) c(if (pte[[1]] == '<-' && is.call(pte[[2]]) && pte[[2]][[1]] == '$') as.character(pte[[2]][[3]]),getLValueDollarRHS(pte))));
getLValueDollarRHS(body(setVarType));
## [1] "Species"      "Sepal.Length"

Demo on a built-in function:

getLValueDollarRHS(body(xtabs));
## [1] "data"               "..."                "exclude"            "drop.unused.levels" "sparse"

Need Your Help

Deleting Multiple Items from a ListBox; Update in XML

c# winforms linq-to-xml

I use an XML file to store from and display the contents on a ListBox.

Resource not found in asp.net mvc AsyncController

c# asp.net-mvc-2 asynccontroller

I just converted a my controller to asyncController in asp.net mvc 2. (ie: spliting action method About into AboutAsync and AboutCompleted). However, I am getting a resource not found error.