Search code examples
rsample

Sampling for a row from a matrix yields empty data


I have a matrix named "fida", from which I have randomly sampled certain number of rows. On these rows I am running a set of commands at the end of which I have a condition which if true, i want to sample another row randomly from the same matrix which is not any of the rows sampled earlier.

For doing this I have a condition. But before that itself when i use the same command to sample from the matrix gives me an empty data

reps=5 #number of samples
randreps=sample(nrow(fida), size = reps, replace = F)

for (loop in randreps)
{calculate a}
if(a==0)
{loop=sample(nrow(fida), size = 1, replace = F)
calculate a}

But when I run this, the second sample always gives empty data and a cannot be calculated. When I go back and check my dataframe "fida" for the row that has been selected, there is data in that row. I do not know what is wrong and any help will be much appreciated.


Solution

  • You could approach this problem in the following manner.

    set.seed(357)
    xy <- matrix(1:30, nrow = 10)
    
    original.rows <- sample(10, size = 3, replace = FALSE)
    original <- xy[original.rows, ]
    
    # Your calculations.
    
    # Sample from the original matrix again, but without the already sampled
    # samples.
    middle <- xy[-original.rows, ]
    output.row <- sample(nrow(middle), size = 3, replace = FALSE)
    output <- xy[output.row, ]
    

    In other words, you have a matrix that holds only the unsampled rows, which serves as a source of new rows for your calculations.