Efficient multiplication of columns in a data frame
A data.table
solution will avoid lots of internal copying while having the advantages of not spattering the code with $
.
library(data.table)
DT <- data.table(df)
DT[ , new := column1 * column2]
As Blue Magister said in comments,
df$new_column <- df$column1 * df$column2
should work just fine. Of course we can never know for sure if we don't have an example of the data.
A minor, somewhat less efficient, version of Sacha's Answer is to use transform()
or within()
df <- transform(df, new = column1 * column2)
or
df <- within(df, new <- column1 * column2)
(I hate spattering my user code with $
.)