How do you change the values in a data.table column within a function?
DF = data.table(ID = c("b","b","b","a","a","c"), a = 1:6, b = 7:12, c = 13:18)
change_it <- function(data_table) {
data_table[[column]] <- 73
}
column = 'a'
change_it(DF, column) # Nothing happens because data_table is not a reference (or something)
DF[[column]] <- 73 # The change happens
CodePudding user response:
It works with the := operator like so:
DF = data.table(ID = c("b","b","b","a","a","c"), a = 1:6, b = 7:12, c = 13:18)
change_it <- function(data_table) {
data_table[, c('a') := 73]
}
change_it(DF) # The change occured
This would change the values in-place.
CodePudding user response:
One way to solve your problem:
change_it <- function(data_table) {
set(data_table, j="a", value=73)
}
# apply the change
change_it(DF)