myfatson
myfatson

Reputation: 547

How can I create a function that generates an empty vector and then populate it with results of a for-loop?

I am trying to convert the following for-loop into a function where I can vary sample size.

This code pulls 500 random samples between 1-365 and assesses if the value '1' exists. If 1 exists then the result of the 'all' function is FALSE. The for-loop then runs this 1000 times and populates the empty vector t.

t <- vector()

for (i in 1:1000){
  t[i] <- all(ifelse(data.frame(table(sample(1:365, 500, replace=TRUE)))$Var1 == 1, FALSE, TRUE))
}

t

I want to write a custom function based off this that allows me to vary the sample size. This is what I have so far.

t <- vector()

function.a <- function(sample.size){
  for (i in 1:1000){
  t[i] <- all(ifelse(data.frame(table(sample(1:365, sample.size, replace=TRUE)))$Var1 == 1, FALSE, TRUE))
}
  return(t)
}

function.a(500)

Is there any way to include the generation of an empty vector such as 't' in the function and condense this a little more?

Edited code as per feedback from u/r2evans :

function.a <- function(sample.size){
  t <- vector()  
  for (i in 1:1000){
  t[i] <- all(ifelse(data.frame(table(sample(1:365, sample.size, replace=TRUE)))$Var1 == 1, FALSE, TRUE))
}
  return(t)
}

function.a(500)

Edit 2: Final code

function.a <- function(sample.size){
  x <- vector()
  for (i in 1:1000){
  x[i] <- !any(data.frame(table(sample(1:365, sample.size, replace=TRUE)))$Var1 == 1)
}
  return(x)
}

function.a(750)

Edit: Final final answer!

x <- vector(length = 1000)

for (i in 1:1000){
  x[i] <- !any(sample(1:365, 500, replace=TRUE) == 1) 
}

function.a <- function(sample.size){
  x <- vector(length= 1000)
  for (i in 1:1000){
  x[i] <- !any(sample(1:365, sample.size, replace=TRUE) == 1) 
}
  return(x)
}
function.a(750)

Upvotes: 1

Views: 50

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389215

So you want FALSE if there is atleast one 1 in table(sample(1:365, sample.size, replace=TRUE)).

I would have written this as :

function.a <- function(sample.size){
  replicate(1000, !any(table(sample(1:365, sample.size, replace=TRUE)) == 1))
}
t1 <- function.a(500)

Upvotes: 0

Related Questions