dimanche 28 mai 2023

With R, how do I get a random number from a varying vector that can be of length 1

I'm using sample(2:ncol(matrix),1) to get the number of a random collumn in my matrix, excluding column 1. The matrix increases in size as my loop iterates. It works as it should, except that when the number of columns is 2, instead of automatically returning 2 with a 100% probability, it sometimes returns 1. That's because when the length of the object from which to sample is 1, sample considers it to range from 1 to that number. How can I avoid this, or is there a better function for me to use? Thanks

I've tried sample(2:ncol(matrix),1), but when ncol(matrix)=2, it can return 1, which should not happen for my code.




Aucun commentaire:

Enregistrer un commentaire