Reputation: 1002
I have a data set of 2 columns (say X and Y). i need to generate 100 samples of both columns with replacement where each sample has 10 rows.
The X and Y values should be related. That means basically i need to re sample rows.
This is my work so far to generate 1 sample,
set.seed(326581)
X1=rnorm(10,0,1)
Y1=rnorm(10,0,2)
data=data.frame(X1,Y1)
library("dplyr", lib.loc="~/R/win-library/3.5")
sample_n(data,10,replace = T)
since i need 100 samples, i tried the replicate function in R. But it didnt work. So i tried to use a loop.
rex=c()
rey=c()
for(i in 1:100)
{
rex[i]=sample_n(data,10,replace=T)[,1]
rey[i]=sample_n(data,10,replace=T)[,2]
}
but it didnt give the desired output.
Can anyone help me to figure out the error ? or is there any function (like replicate function to sampling from 1 column) to this in much more easily ?
Upvotes: 0
Views: 711
Reputation: 50668
Do you mean something like this?
Using base R's sample
# Sample 100 rows from data
set.seed(2017)
idx <- sample(nrow(data), 100, replace = T)
# Store samples in a 100x2 data.frame
df.smpl <- data[idx, ]
Using dplyr::sample_n
set.seed(2017)
df.smpl <- data %>%
sample_n(100, replace = T)
Both methods will store 100 samples drawn (with replacement) from the rows of data
in a new data.frame
of dimension
dim(data.smpl)
#[1] 100 2
Or if you prefer samples to be in a list
of vectors
lapply(idx, function(i) as.numeric(data[i, ]))
To repeat drawing 10 rows from data
100 times you can use replicate
set.seed(2017);
lst <- replicate(
100,
df.smpl <- data %>% sample_n(10, replace = T),
simplify = FALSE)
This generates a list
with 100 data.frame
s
length(lst)
[1] 100
each with dimension 10x2
sapply(lst, dim)
#[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
#[1,] 10 10 10 10 10 10 10 10 10 10 10 10 10 10
#[2,] 2 2 2 2 2 2 2 2 2 2 2 2 2 2
#[,15] [,16] [,17] [,18] [,19] [,20] [,21] [,22] [,23] [,24] [,25] [,26]
#[1,] 10 10 10 10 10 10 10 10 10 10 10 10
#[2,] 2 2 2 2 2 2 2 2 2 2 2 2
#[,27] [,28] [,29] [,30] [,31] [,32] [,33] [,34] [,35] [,36] [,37] [,38]
#[1,] 10 10 10 10 10 10 10 10 10 10 10 10
#[2,] 2 2 2 2 2 2 2 2 2 2 2 2
#[,39] [,40] [,41] [,42] [,43] [,44] [,45] [,46] [,47] [,48] [,49] [,50]
#[1,] 10 10 10 10 10 10 10 10 10 10 10 10
#[2,] 2 2 2 2 2 2 2 2 2 2 2 2
#[,51] [,52] [,53] [,54] [,55] [,56] [,57] [,58] [,59] [,60] [,61] [,62]
#[1,] 10 10 10 10 10 10 10 10 10 10 10 10
#[2,] 2 2 2 2 2 2 2 2 2 2 2 2
#[,63] [,64] [,65] [,66] [,67] [,68] [,69] [,70] [,71] [,72] [,73] [,74]
#[1,] 10 10 10 10 10 10 10 10 10 10 10 10
#[2,] 2 2 2 2 2 2 2 2 2 2 2 2
#[,75] [,76] [,77] [,78] [,79] [,80] [,81] [,82] [,83] [,84] [,85] [,86]
#[1,] 10 10 10 10 10 10 10 10 10 10 10 10
#[2,] 2 2 2 2 2 2 2 2 2 2 2 2
#[,87] [,88] [,89] [,90] [,91] [,92] [,93] [,94] [,95] [,96] [,97] [,98]
#[1,] 10 10 10 10 10 10 10 10 10 10 10 10
#[2,] 2 2 2 2 2 2 2 2 2 2 2 2
#[,99] [,100]
#[1,] 10 10
#[2,] 2 2
Upvotes: 1