简体   繁体   中英

Add character to element within a matrix in R

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". EG 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 (ie 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 (eg "19 2") which I assume was the position in matrix that was sampled.

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="")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM