Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use character input to define function in R

I have an input data set, which may look something like this:

DF=data.frame(
    Variable = c("Test1", "Test2", "Test3"), 
    Distribution = c("Normal", "Exponential","Poisson"),
    Variable = c(2, 3, 4), 
    SD = c(2, NA, NA))

I want to use the random probability functions (e.g. rnorm rexp and rbinom) using the distributions given in the data frame DF.

So, how do I turn the text input into the correct functions?

I want to use the corresponding values in the Variable and SD columns as the mean values/standard deviations if appropriate.

like image 581
sym246 Avatar asked Apr 17 '26 07:04

sym246


1 Answers

@r.user.05apr solution is working, but involves some expression parsing which is not needed here. We might get this a lot easier by creating a list of functions to use them later.

# generating data:
DF=data.frame(
  Variable = c("Test1", "Test2", "Test3"), 
  Distribution = c("Normal", "Exponential","Poisson"),
  VariablePrm = c(2, 3, 4), 
  SD = c(2, NA, NA),
  stringsAsFactors = FALSE)

# creating function list and selecting this functions by Distribution column
fun_vec <- c(Normal=rnorm, Exponential=rexp, Poisson=rpois)
DF$fun <- fun_vec[DF$Distribution]

# if SD is NA then simply call function only with variablePrm
# else call with sd
# 10 is the number of observations to generate
generate <- function(x) {
  if(is.na(x$SD)){
    x$fun(10, x$VariablePrm)
  }else{
    x$fun(10, x$VariablePrm, x$SD)
  }
}
# if we apply this functions to each row we will get matrix of results
# each column will have 10 rows of generated data for previously selected distribution
apply(DF, 1, generate)
like image 86
bartektartanus Avatar answered Apr 19 '26 20:04

bartektartanus