replace a list of values by another in R

前端 未结 3 930
别跟我提以往
别跟我提以往 2021-02-02 12:01

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 a

相关标签:
3条回答
  • 2021-02-02 12:35

    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.

    0 讨论(0)
  • 2021-02-02 12:37
    matrix(to[match(dd,from)], nrow=nrow(dd))
    

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

    0 讨论(0)
  • 2021-02-02 12:46

    I used a similar for loop as OP and timed the solutions. Theodore's one is fastest by a slight margin, but Martin's is very readable.

    dd<-matrix(sample(from, 100, replace = TRUE),10,10)
    ddr <- dd
    ddm <- dd
    ddt <- dd
    
    benchmark(roman = {
      for (i in 1:length(from)) {
        ddr[ddr == from[i]] <- to[i]
      }},
      martin = {
        map = setNames(to, from)
        ddm[] = map[dd]
      },
    theodore = {ddt <- matrix(to[match(dd,from)], nrow=nrow(dd))},
              replications = 100000
    )
          test replications elapsed relative user.self sys.self user.child sys.child
    2   martin       100000    1.93    1.191      1.91        0         NA        NA
    1    roman       100000    8.23    5.080      8.11        0         NA        NA
    3 theodore       100000    1.62    1.000      1.61        0         NA        NA
    
    0 讨论(0)
提交回复
热议问题