write a function to suggest a data.table in r

To suggest a data.table in R, you can write a function that accepts a data.frame as an argument, and checks whether it can be converted to a data.table. Here's an example function:

main.r
suggest_data_table <- function(df) {
  require(data.table)
  if (!is.data.frame(df)) {
    message("Input is not a data.frame, returning NULL")
    return(NULL)
  }
  dt <- as.data.table(df)
  if (is.null(dt)) {
    message("Could not convert to data.table, returning NULL")
    return(NULL)
  }
  message("Suggested data.table:")
  print(dt)
  return(dt)
}
358 chars
16 lines

This function first checks if the input is a data.frame, and returns NULL if it isn't. It then attempts to convert the data.frame to a data.table using the as.data.table() function from the data.table package. If the conversion fails, the function also returns NULL. If the conversion succeeds, the suggested data.table is printed to the console, and the function returns the data.table.

You can call this function by passing a data.frame as an argument, like this:

main.r
df <- data.frame(a = c(1, 2, 3), b = c("x", "y", "z"))
suggest_data_table(df)
78 chars
3 lines

This will suggest a data.table based on the input dataframe.

gistlibby LogSnag