1

say that I have

df1$name <- c('A','B','C','D','E')
df1$val <- c(1, 2, 3, 4, 5)

and

df2$name <- c('A','B')
df2$val <-c(6,7)

I want to calculate df2 - df1 s.t. df3 will be

df3$name <- df2$name
df3$val <- df2$val-df1$val[df1$name==df2$name]

and "match" the names so that

df3$val<-c(6-1,7-2)

would be the output. I tried doing this but I couldn't get the syntax correct, thanks in advance!

peterni
  • 13
  • 3

2 Answers2

1

We can use a join

library(data.table)
setDT(df2)[df1, val := val - i.val, on = .(name)]

data

df1 <- data.frame(name = LETTERS[1:5], val = 1:5)
df2 <- data.frame(name = LETTERS[1:2], val = 6:7)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Base R:

### your starting data
df1 <- data.frame(name=c('A','B','C','D','E'), val=c(1, 2, 3, 4, 5))
df2 <- data.frame(name=c('A','B'), val=c('6','7'))

### fix strings-to-integers
df2$val <- as.integer(df2$val) # since we want to subtract

### merge and subtract
out <- merge(df1, df2, by = "name")
out$val <- out$val.y - out$val.x
out
#   name val.x val.y val
# 1    A     1     6   5
# 2    B     2     7   5

And as akrun started with, this is a merge/join operation; for good discussion and examples on that, see How to join (merge) data frames (inner, outer, left, right), https://stackoverflow.com/a/6188334/3358272.

r2evans
  • 141,215
  • 6
  • 77
  • 149