Extremely beginner, and the whole concept of doing things randomly in R is something I haven't managed to grasp yet.
My code below is the beginnings of me trying to create a matrix that is made up of a random distribution of the letters a - e (with replacement etc) which is my vector "bob.a". What I then need to do is select a random element from this matrix, and replace it with another sample of "bob.a" (so another random letter, even if that letter ends the same). Ideally I'd then run this through a loop something like 100 times until every element has randomly been replaced (though that every element is replaced is not important over the grand scheme of just making sure I randomly replace elements 100 times).
My code is:
##Create Bob Vector
bob.a<-factor(c(letters[1:5]))
##Check Bob Vector
bob.a
#Matrix creation (Random)
bob.matrix<- matrix(sample(bob.a,25,replace=TRUE),
nrow=5,
ncol=5,
byrow = TRUE)
##Check bobmatrix.v2
bob.matrix
##Random removal (&replace?)
bob.matrix[2,3] <- sample(bob.a,1,replace=TRUE)
sample(bob.matrix,1)
bob.matrix[,] <- sample(bob.a,1,replace=TRUE)
sample(bob.matrix,1) <- sample(bob.a,1,replace=TRUE)
(I'm doing everything very basic and checking every step because I'm in serious need of understanding the core concepts of what I'm doing!)
While I'm sure the answer will involve sample and maybe index, just doing so randomly is totally lost on me right now.
I tried just doing a simple replacement, just to check I knew how to, but that didn't even work because the line
bobmatrix.v2[2,3] <- sample(bob.a,1,replace=TRUE)
Inserts a number value for the text (e.g. replaces position [2,3] with a 1 instead of an a) which has totally thrown me off. The last two lines of code are me trying different things that don't work for what I thought of.
In the random replacement I thought it may use either indexing or sampling but my knowledge of indexing is quite low. And what I've seen online often seems to be based around replacing certain elements (such as all of the "a"'s with something else) or some variation of that, instead of selecting a single random element within the matrix, in the same way that sample does (but being able to replace that element).
Ultimately I need 3 (what I thought were simple) things:
- Select a random element/position in the matrix
- Select a random letter from a vector "sample(bob.a,1)
- Replace 1 with 2 (random element/position with random letter from vector.)
Any help would be appreciated, and while it seems relatively pointless it's a core concept for some programming I'm going to have to be doing over the summer and I really, really want to be able to do and understand what is happening to be sure I can actually do the project I've committed to.
Also, I've not looked into the loop part of this yet, so any guidance there would be great.
Many Thanks
Aucun commentaire:
Enregistrer un commentaire