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
}