Reputation: 465
I generated the following random samples in R:
sample1 <- sample(c(TRUE, FALSE), size, replace= TRUE, c(x, 1-x))
sample2 <- sample(c(TRUE, FALSE), size, replace= TRUE, c(y, 1-y))
sample3 <- sample(c(TRUE, FALSE), size, replace= TRUE, c(z, 1-z))
sample4 <- sample(c(TRUE, FALSE), size, replace= TRUE, c(n, 1-n))
Now I would like to write a function where users just need to input the size (same for all 4) and the respective probabilities x,y,z,n
samplegenerator <- function(size, x, y, z, n){
...
}
After running the function the user should have 4 samples stored in his working directory under the respective titles (sample1, sample2, sample3, sample4) just as he would have if he would run the sample function and store the output like above.
Since I'm an R newbie I've been struggling with this. Any suggestions?
Thanks in advance!
Upvotes: 2
Views: 87
Reputation: 886948
You could use list2env
to get the "sample" objects in the global environment.
samplegenerator <- function(size, ...){
args <- as.list(match.call())[-(1:2)]
lst <- lapply(args, function(x) sample(c(TRUE, FALSE),
size, replace=TRUE, c(x, 1-x)))
list2env(setNames(lst, paste0('sample', seq_along(args))), envir=.GlobalEnv)
}
samplegenerator(20, 0.3, 0.4,0.5,0.9)
sample3
#[1] TRUE TRUE FALSE TRUE FALSE FALSE TRUE FALSE TRUE TRUE FALSE TRUE
#[13] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE
sample4
# [1] TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE
#[13] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
Upvotes: 1
Reputation: 490
There is a straightforward answer to your question, which is to use assign()
to the global environment, like so:
samplegenerator <- function(size, x, y, z, n){
sample1 <- sample(c(TRUE, FALSE), size, replace= TRUE, c(x, 1-x))
sample2 <- sample(c(TRUE, FALSE), size, replace= TRUE, c(y, 1-y))
sample3 <- sample(c(TRUE, FALSE), size, replace= TRUE, c(z, 1-z))
sample4 <- sample(c(TRUE, FALSE), size, replace= TRUE, c(n, 1-n))
assign("sample1", sample1, envir = .GlobalEnv)
assign("sample2", sample2, envir = .GlobalEnv)
assign("sample3", sample3, envir = .GlobalEnv)
assign("sample4", sample4, envir = .GlobalEnv)
}
x <- .3
y <- .6
z <- .1
n <- .9
size <- 10
samplegenerator(size, x, y, z, n)
This sets, in the global environment, the values sample 1-4 to the variable names as specified.
However, ask yourself the question why you want to do this. This kind of behaviour can be kind of hacky and clutter your workspace, while there may be a more elegant solution.
Upvotes: 0