简体   繁体   中英

data.table column assignments as a stored function

I have a table in an R package that I'm writing which is very large. To keep the size down for distribution, I'm eliminating all columns from the table that can be calculated from other columns. For example, day of week can be calculated from the date, so I leave out day of week from the package data set. However, I want to make it convenient to recalculate these columns in a standard way for anyone that uses the package. I'd like to do it with the data.table in place assignments, for the sake of efficiency. I'm imagining something like this:

dt = myPackageData  # minimal data set included in the package
extend_dow = function(your_data_table) {
  your_data_table[,`:=`(day_of_week = lubridate::wday(my_date))]
}
extend_dow(dt)

And then dt would have the day_of_week column available for use.

The problem that I'm running into is that the in-place assignment of the new column seems to be occurring in a lower level environment, and the data.table that I pass to the function doesn't actually get modified.

Does anyone know how I can store the complete formula for a new column, which can be applied using a single function call to the same data.table that the user passes to the function?

I figured it out. The example that I posted above does work, but only if you make a data.table::copy of the data.table before feeding it to the function, like so:

library(myPackage)
library(data.table)
dt = copy(myPackageData)
extend.weekday = function(your_data_table) {
  your_data_table[,`:=`(day_of_week = lubridate::wday(my_date))]
}
extend.weekday(dt)

The mistake in my example is that I was assigning the package data directly to dt = myPackageData , without making a copy . In that case, the column extension does not get applied. I would guess that this is because the object is still referencing the package data somehow, which prevents any changes from being applied when the function is executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM