Add equal lines from different tables in R

Asked

Viewed 43 times

1

I am having several tables with three columns as output, for example:

Inicial            Final        Mudanca
       1                 1              200
       1                 3              500
       3                 1               250
       3                 3               175
Tabela 2
   Inicial         Final        Mudanca
       1                 3              180
       1                 5              265
       3                 3               147
       3                  7              155

I need to add the last column of the tables (Change) so that the rows of the Initial and Final column of Table 1 are equal to each row of the Initial and Final of Table 2, generating a table of this type

Inicial            Final        Mudanca
       1                 1          200
       1                 3           680
       1                 5           265
       3                 1            250
       3                 3            322
       3                 7           155

I’m trying this way, but it’s making a mistake:

for (row in 1:nrow(t1) {
  t2[t2$Inicial == row$Inicial && t2$Final == row$Final,t2$Mudanca] <- row$Mudanca + t2[t2$Inicial == row$Inicial && t2$Final == row$Final,t2$Mudanca]
}

Can someone help me, please?

1 answer

0


Through two ways I managed to solve this:

A) using Aggregate and rbind

aggregate(Changes ~ ., rbind(t1, t2), sum)

B) or creating a new column with the sums:

joined = merge(t1,t2,by = c("Initial","Final"),all=T)
    joined["Changes.final"] <- apply(joined[,c("Changes.x","Changes.y")],
                                 FUN = function(x)sum(x,na.rm=T), MARGIN = 1)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.