#' @title Create a new variable within the data frame
#' @description
#' \code{gen} easily create a new variable within the data frame
#' @param data data frame
#' @param var name of a new variable
#' @param expr value or Expression: See examples below.
#' @details
#' The value of the variable are specified by \code{expr} argument.
#' If \code{expr} is not specified, \code{gen} generates \code{NA} by default.
#' @seealso \code{\link{egen}}
#' @keywords value label, label levels
#' @author Myo Minn Oo (Email: \email{dr.myominnoo@@gmail.com} |
#' Website: \url{https://myominnoo.github.io/})
#' @examples
#' str(infert)
#'
#' # convert age into months
#' df1 <- gen(infert, age.month, age * 12)
#' head(df1)
#'
#' # age category
#' df2 <- gen(infert, age.cat, ifelse(age < 25, 1, ifelse(age >= 25 & age < 35, 2, 3)))
#' head(df2)
#'
#' # age category
#' summary(infert$age)
#' df3 <- gen(infert, age.cat, cut(age, c(21, 35, 44)))
#' head(df3)
#'
#' # create new variable with mean value
#' df4 <- gen(infert, age.mean, mean(age))
#' head(df4)
#'
#' # new NA variable
#' df5 <- gen(infert, age.cat)
#' head(df5)
#' @export
gen <- function(data, var, expr = NULL)
{
if (!is.data.frame(data)) stop("Input must be a data frame.")
var <- deparse(substitute(var))
expr <- deparse(substitute(expr))
txt <- paste0("data$", var)
if (length(eval(parse(text = txt))) == 0) {
if (expr == "NULL") {
eval(parse(text = paste0(txt, " <- NA")))
} else {
eval(parse(text = paste0(txt, " <- with(data, ", expr, ")")))
}
} else stop(paste0(var, " already exists."))
return(data)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.