简体   繁体   中英

I need to sample n groups of n random rows from df in R

I want to iterate n times a function that draws n rows at random from a dataframe. Since the groups consist each of 785 rows, the function is this:

randomSample = function(merged_df_1, n) { 
  return( merged_df_1[sample(nrow(merged_df_1), 785),] )
}

To iterate this function 10 times, I tried this code

n=10
lapply(rep(1, n), randomSample)

But I get the following error message

"Error in sample.int(length(x), size, replace, prob) : invalid first argument"

What's happening is that lapply takes the rep(1,n) vector and uses it as the first argument of your function. I guess you could do this:

randomSample = function(n, merged_df_1) { 
#note that the function doesn't really use n inside it, if you want so, you should #replace 785 for n and use rep(n,n) inside the lapply call
  return(merged_df_1[sample(nrow(merged_df_1), 785),] )
}

n=10
lapply(rep(1,n), function(x)randomSample(x,merged_df_1))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM