I have two tables, and I'm trying to find values from one to add to the values in the other. I am currently using two loops, but they are slow. I am new to R and know that I should avoid a loop to speed things up, but I cannot figure out how to do this.
Table 1 (several thousand rows, 37 columns):
type cat1 cat2 cat3 ... cat36
1 2 3 2 7
3 6 2 1 9
2 4 6 7 4
3 5 7 8 2
5 2 2 9 1
4 3 1 2 3
1 8 1 4 4
... Table2 (36 rows, 5 columns):
type1 type2 type3 type4 type5
cat1 2 3 4 3 8
cat2 8 5 5 2 6
cat3 7 5 1 3 5
...
cat36 4 7 2 8 9
I want to change each value in table 1 by adding the corresponding value (corresponding to five types and 36 categories) from table 2. Here are the desired results:
type cat1 cat2 cat3 ... cat36
1 4 11 9 11
3 10 7 2 11
2 7 11 12 11
3 9 12 9 4
5 10 8 14 10
4 6 3 5 11
1 10 9 11 8
... Here is my current (slow) code:
for (i in 1:36) { for (j in 1:nrow(Table1)) { Table1[j,i+1] = Table1[j,i+1] + Table2[i,Table1[j,1]] } }
source share