简体   繁体   English

我需要从R中的df采样n组n个随机行

[英]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. 我想迭代n次从数据帧随机绘制n行的函数。 Since the groups consist each of 785 rows, the function is this: 由于组由785行组成,因此功能如下:

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 若要将此功能重复10次,我尝试了这段代码

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" “ sample.int(length(x),size,replace,prob)中的错误:无效的第一个参数”

What's happening is that lapply takes the rep(1,n) vector and uses it as the first argument of your function. 发生的是lapply接受rep(1,n)向量并将其用作函数的第一个参数。 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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