I have a dataframe with any of these values.
from=c("A","C","G","T","R","Y","M","K","W", "S","N")
and I want to replace accordingly with
to=c("AA","CC","GG","TT","AG","CT","AC","GT","AT", "CG","NN")
What is the best way to do that , loop over all values to replace? or loop over matrix position. or any other solution?
dd<-matrix(sample(from, 100, replace=TRUE), 10)
dd
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "K" "S" "G" "T" "R" "N" "A" "C" "W" "M"
[2,] "Y" "K" "S" "G" "T" "R" "N" "A" "C" "W"
[3,] "M" "Y" "K" "S" "G" "T" "R" "N" "A" "C"
[4,] "W" "M" "Y" "K" "S" "G" "T" "R" "N" "A"
[5,] "C" "W" "M" "Y" "K" "S" "G" "T" "R" "N"
[6,] "A" "C" "W" "M" "Y" "K" "S" "G" "T" "R"
[7,] "N" "A" "C" "W" "M" "Y" "K" "S" "G" "T"
[8,] "R" "N" "A" "C" "W" "M" "Y" "K" "S" "G"
[9,] "T" "R" "N" "A" "C" "W" "M" "Y" "K" "S"
[10,] "G" "T" "R" "N" "A" "C" "W" "M" "Y" "K"
I used loop over all from to to.
myfunc<-function(xx){
from=c("A","C","G","T","R","Y","M","K","W", "S","N");
to=c("AA","CC","GG","TT","AG","CT","AC","GT","AT", "CG","NN");
for (i in 1:11){
xx[xx==from[i]]<-to[i];
}
return(xx);
}
it worked great for small matrix, but takes a long time for big matrix. Any effcient solution?
Thanks
replace() function in R Language is used to replace the values in the specified string vector x with indices given in list by those given in values. It takes on three parameters first is the list name, then the index at which the element needs to be replaced, and the third parameter is the replacement values.
In the R Commander, you can click the Data set button to select a data set, and then click the Edit data set button. For more advanced data manipulation in R Commander, explore the Data menu, particularly the Data / Active data set and Data / Manage variables in active data set menus.
The mutate() function is used to modify a variable or recreate a new variable. Variable are changed by using the name of variable as a parameter and the parameter value is set to the new variable.
Create a map
map = setNames(to, from)
and go from A to B
dd[] = map[dd]
The map serves as a look-up, associating 'from' names with 'to' values. The assignment preserves matrix dimensions and dimnames.
matrix(to[match(dd,from)], nrow=nrow(dd))
match
returns a vector without dimensions, so you need to recreate the matrix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With