R - replace values in data frame using lookup table

北慕城南 提交于 2019-11-30 16:14:15

问题


I was having some trouble lately trying to replace specific values in a data frame or matrix by using a lookup-table.

So this represents the original.data to be modified ...

    V1  V2  V3  V4  V5  V6  V7  V8  V9 V10 V11 V12 V13 V14
1  255 255 255 255 255 255 255 255 255 255 255 255 255 255
2  255 255 255 255 255 255 255 255   3   3 255 255 255 255
3  255 255 255 255 255   1   3   3   3   3   3 255 255 255
4  255 255   5   5   5   1   3   3   4   4   3 255 255 255
5  255   5   5   5   5   1   3   4   4   4   4 255 255 255
6  255   5   5   5   1   3   3   3   4   4   3   3 255 255
7  255 255   5   1   3   3   3   3   6   6   6   3 255 255
8  255 255   1   1   1   1   2   2   3   3   6   3 255 255
9  255 255   1   1   1   2   2   2   2   2   3   3   3 255
10 255 255 255   1   2   2   2   2   2   2   2   3   3 255
11 255 255 255   2   2   2   2   2   7   7   7   2 255 255
12 255 255 255   2   2   8   8   8   7 255 255 255 255 255
13 255 255 255 255   8   8 255 255 255 255 255 255 255 255
14 255 255 255 255 255 255 255 255 255 255 255 255 255 255

... and following may be the lookup.table (rows=1:9, column1="Sub", column2="Main"):

  Sub Main
1   1    1
2   2    2
3   3    3
4   4    4
5   5    5
6 255  255
7   6    3
8   7    2
9   8    2

The aim is to compare e.g. original.data[11,11] [7] with lookup.tabel[8,"Sub"] [7]

... and write a new matrix modified.data[11,11] with lookup.table[8,"Main"] [2]. Until now all I came up with is using for-loops and an if-statement,

for (i in 1:ncol(original.data)){
  for (j in 1:nrow(lookup.table)){
    if (original.data[i,i]==lookup.table[j,1]){
      origingal.data[j,i]<-lookup.table[j,2]
    }
  }
}

which leads to

Error in origingal.data[j, i] <- lookup.table[j, 2] : 
  object 'origingal.data' not found

but i cannot figure out my errors in reasoning.

I'd love to get some hints.

Thanks

\\\\\PROBLEM SOLVED

for (i in 1:ncol(original.data)){
  for (j in 1:nrow(original.data)){
    for (x in 1:nrow(lookup.table)){
      if (original.data[j,i]==lookup.table[x,1]){
        original.data[j,i]<-lookup.table[x,2]
      }
    } 
  }
}

... works, but this is a much faster method:

for(i in 1:nrow(lookup.table)){
  c<-lookup.table[b,2]
  d<-lookup.table[b,3]
  original.data_modified[original.data == c] <- d
}

回答1:


you can try :

# x the original.data (a matrix)
# y the lookup.table
x2 <- y[match(x, y[,1]),2]
dim(x2) <- dim(x)
table(x, x2)
     x2
x       1   2   3   4   5 255
  1    13   0   0   0   0   0
  2     0  22   0   0   0   0
  3     0   0  29   0   0   0
  4     0   0   0   8   0   0
  5     0   0   0   0  11   0
  6     0   0   4   0   0   0
  7     0   4   0   0   0   0
  8     0   5   0   0   0   0
  255   0   0   0   0   0 100


来源:https://stackoverflow.com/questions/22475400/r-replace-values-in-data-frame-using-lookup-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!