Reputation: 31
I'm looking for a way to add a character to a sample of an element within a matrix. I create then sample a matrix containing a random distribution of the letters a - e, and what I'm hoping to do next is create a "speciation" event in which whatever element I sample, becomes a "new species". E.G. Sample of matrix is a "c", then I add a "2" to it, so it becomes "c2".
The base code I run this under right now is:
##Create Species Vector
species.v<-letters[1:5]
species.v<as.character(species.v)
##Check species Vector
species.v
#Matrix creation (Random)
orig.neutral<- matrix(sample(species.v,25,replace=TRUE),
nrow=5,
ncol=5)
##Check neutral.matrix
orig.neutral
##Random Replacement
orig.neutral[sample(length(orig.neutral),1)]<-as.character(sample(orig.neutral,1))
orig.neutral
What I would like to do is then swap the random replacement
orig.neutral[sample(length(orig.neutral),1)]<-as.character(sample(orig.neutral,1)
for a way to add a 2 to whatever the contents of the sample is.
In an ideal world I'd also be able to add further speciation if there is already a number within that cell (i.e. if it is already "b2" I could make it "b3" but I think I could do that with if functions anyway, just need to code to actually add the 2 in the first place. (Though having thought about it more that'd only end up with b23... which is not what I want at all!)
Any help would be appreciated
many thanks
Edit:
Using paste as recommended by @sam81, I have added the line:
neutral.v0<-orig.neutral ##keep original to compare
neutral.v0[sample(length(neutral.v0),1)] = paste("2", sep=" ")
which only replaces whatever the sample is with 2, as opposed to adds 2 to whatever was in the sample. I tried paste((sample(length(neutral.v0),1)),"2",sep="") but that just returned numbers into the matrix (e.g. "19 2") which I assume was the position in matrix that was sampled.
Upvotes: 0
Views: 370
Reputation: 633
you can use paste
to add a character, for example, the following line will add a 2 to each element of the matrix:
orig.neutral = paste(orig.neutral, "2", sep="")
if you want to add a 2 only to a single, randomly selected element of the matrix, then you can do the following:
elIdx = sample(length(neutral.v0),1) #index of a randomly selected element
orig.neutral[elIdx] = paste(orig.neutral[elIdx], "2", sep="")
Upvotes: 1