Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace a list of values by another in R

Tags:

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

like image 274
Ananta Avatar asked Apr 09 '13 20:04

Ananta


People also ask

How do I replace a list of values in R?

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.

How do I change data in R?

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.

How do I change the value of a variable in R?

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.


2 Answers

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.

like image 105
Martin Morgan Avatar answered Sep 16 '22 12:09

Martin Morgan


matrix(to[match(dd,from)], nrow=nrow(dd))

match returns a vector without dimensions, so you need to recreate the matrix.

like image 33
Theodore Lytras Avatar answered Sep 16 '22 12:09

Theodore Lytras