-1

Following this thread computing probabilities

the verified answer contained a for loop and prop.tables. I want to combine both into one single function such that every "b" should represent a column of a dataframe.

For example :

df.base<-as.data.frame(ncol(dataframe0),replicate(vector("numeric",1000)))

where each column in dataframe0 contains integer or continuous values that would be sampled 1000 times.I would also like to point out that when the first column in dataframe0 was sampled ,its values must be stored in df.base[,1]

computeFun<-function(dataframe){
   set.seed(1234)
   for (i in 1:1000){
      df.base[i] <- sample(dataframe0[,1:ncol(dataframe)], size=1, replace = T)
   return(df.base]}

I was really trying to figure out a way for days now but I couldn't.

Thank you

Marco_CH
  • 3,243
  • 8
  • 25
Euler
  • 29
  • 1
  • 6
  • The function is missing a second closing `}`. Can you make your question reproducible? We don't have access to the `dataframe0`. – Roman Luštrik Jan 21 '22 at 21:22
  • Thank you for you quick reply Roman, here is an example of dataframe0`dataframe0<-as.data.frame(replicate(4,vector("numeric",900))) x<-rep(1:900) dataframe0[,1:ncol(dataframe0)]<-replicate(ncol(dataframe0),sample(x))` – Euler Jan 21 '22 at 22:54
  • I tried this but it didn't work, `sampleVector<-function(numV,x){ df.base<-as.data.frame(replicate(numV,vector("numeric",1000))) j<-1 irow<-0 for (j in 1:numV){ if (irow==1){ set.seed(1234) for (i in 1:1000){ df.base[i] <- sample(x[,j], size=1, replace = T) } irow<-1 } } return(df.base) } p<-sampleVector(ncol(dataframe0),dataframe0)` – Euler Jan 22 '22 at 01:14
  • 1
    Thank you Roman and everyone whoever just have the intention to help :) I figured out the solution, it was pretty simple : – Euler Jan 22 '22 at 20:10

1 Answers1

0
sampleLoop<-function(x){
    set.seed(1234)
    for (i in c(1:ncol(x))){
        df.base[,i] <-replicate(1000,sample(x = x[,i],size = 1,replace = T))
    }
    return(as.data.frame(df.base))
}
test.sample2<-sampleLoop(dataframe0)

I had to use replicate() instead of a for loop for sampling then I used the for loop to loop through the columns. In other words, the replicate function took care of the rows while the for loop takes care of the columns.

Exactly as central defenders in soccer do, one takes care of air balls where the other handles balls on the ground :)

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Euler
  • 29
  • 1
  • 6
  • 1
    Your indentation was inconsistent and your code block wasn't correctly formatted. I've made an [edit] to your answer to attempt to correct this. Please review, however, to ensure that it's consistent with your expectations. If not, please [edit] to resolve. – Jeremy Caney Jan 23 '22 at 00:18