#' Creates the code to create a data frame by text input.
#'
#' @code{textdf(df)}
#'
#' @param df an existing data frame in the working directory environment
#'
#' @details Useful when using an example data frame in a tutorial, this function
#' will produced the text required to create that data frame by copying and pasting
#' into R without anything further. The resulting data frame is called 'NewDF'
#'
#' @examples
#' textdf(mtcars)
textdf = function(df){
cat("NewDF = data.frame(\n")
for(c in 1:ncol(df)){ # for each column of the data frame in turn
Fac = "" # character which will be 'factor' when appropriate
XF = "" # character which will be a closing bracket for factor when appropriate
N = names(df)[c] # get the name of the variable
X = df[,c] # get the variable
if(class(X)=="numeric" | class(X)=="integer") {
X = toString(X)
} else {
if(class(X)=="factor"){
Fac = "factor("
XF = ")"
}
X = toString(paste0('"',as.character(df[,c]),'"'))
X = gsub('\\" NA \\"','NA',X)
}
cat(N,"=",Fac,"c(",X,")",XF,",\n")
}
cat("row.names = c(",toString(paste0('"',as.character(rownames(df)),'"')),"))\n")
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.