Search code examples
rclassdataframemode

Writing a user-function to return column position, column name, mode and class for every variable


I need to write a user-defined function that, when applied to a data frame, will return the column position, the column name, the mode, and the class for each variable. I am able to create one that returns mode and class, but I keep getting errors when I include the position/name. I have been doing this,

myFunction <- function(x) { 
    data.frame(mode(x), class(x))
  }
data.frame(names(myData), myFunction(myData))

and it returns the correct info, but it doesn't combine it into a single function I need. Any advice?


Solution

  • You can combine it as follows:

    myFunction <- function(x)
       data.frame(mode(x), class(x), cname=names(x), cpos=1:ncol(x))