Home > Back-end >  How to select data.table columns by partial string match and update them by a constant multiplicatio
How to select data.table columns by partial string match and update them by a constant multiplicatio

Time:10-05

I have a large data.table with several columns, where some contain values in Cubic Feet. These are marked by an added "_cft" at the end of the column name. I want to convert the values of these columns to m³ b multiplying them with a constant and returning the updated value. I can already select the columns and multiply them, but am not able to replace the existing values.

My code looks like follows:

dt <- dt[, lapply(.SD, function(x) x * 0.0283168), .SDcols= grepl("_cft", names(dt))]

This however only returns me the columns I converted to the data.table, but I want to keep all the columns in the original data.table. I have already tried using the :=operator, but it results in an error:

"Error: unexpected symbol in dt <- dt[, `:=` lapply"

How can I do this?

CodePudding user response:

Note that you should not combine <- with := because the latter works by reference.
Your error message suggests that you did not do the assignment properly. you need to specify the columns you want to assign to. Doing something like

 dt[, `:=` lapply(.SD, function(x) x * 0.0283168), .SDcols= grepl("_cft", names(dt))] 

will not work, and that's why you got that error message.

Try the following code:

cols = grep("_cft", names(dt))
dt[, (cols) := lapply(.SD, function(x) x * 0.0283168), .SDcols=cols]
# or simply
dt[, (cols) := lapply(.SD, `*`, 0.0283168), .SDcols=cols]
  • Related