So lets say I have the following data.frames:
df1 <- data.frame(y = 1:10, z = rnorm(10), row.names = letters[1:10])
df2 <- data.frame(y = c(rep(2, 5), rep(5, 5)), z = rnorm(10),
row.names = letters[1:10])
And perhaps the "equivalent" data.tables:
dt1 <- data.table(x = rownames(df1), df1, key = 'x')
dt2 <- data.table(x = rownames(df2), df2, key = 'x')
If I want to do element-wise operations between df1 and df2, they look something like
dfRes <- df1 / df2
And rownames() is preserved:
R> head(dfRes)
y z
a 0.5 3.1405463
b 1.0 1.2925200
c 1.5 1.4137930
d 2.0 -0.5532855
e 2.5 -0.0998303
f 1.2 -1.6236294
My poor understanding of data.table says the same operation should look like this:
dtRes <- dt1[, !'x', with = F] / dt2[, !'x', with = F]
dtRes[, x := dt1[,x,]]
setkey(dtRes, x)
(setkey optional)
Is there a more data.table-esque way of doing this?
As a slightly related aside, more generally, I would have other columns such as factors in each data.table and I would like to omit those columns while doing the element-wise operations, but still have them in the result. Does this make sense?
Thanks!