I'm trying to set a series of values in data.table using the below code:
db[, `:=`(paste("PAID", c("A", "B", "C"), sep = "_") = .SD * COST, paste("PAID_NET", c("A", "B", "C"), sep = "_") = .SD * COST * (1 - TAX)) , .SDcols = paste("PRICE", c("A", "B", "C"), sep = "_")]These would work if there wasn't apaste involved, but there is, so it doesn't.
Desired behaivour is that 6 new columns are created, PAID_A, PAID_B, PAID_C, PAID_NET_A, PAID_NET_B, PAID_NET_C, based on SOLD_A, SOLD_B, SOLD_C, COST and TAX.
What's going wrong?
1 Answer1
Setting the names on the lhs of= wouldn't work as expected. We can instead do
nm1 <- paste("PAID", c("A", "B", "C"), sep = "_")nm2 <- paste("PAID_NET", c("A", "B", "C"), sep = "_") nm3 <- paste("PRICE", c("A", "B", "C"), sep = "_")db[, c(nm1, nm2) := c(.SD * COST, .SD * COST * (1 - TAX)), , .SDcols = nm3]Or another option issetNames
db[, `:=`(setNames(.SD * COST, .SD * COST * (1 - TAX), c(nm1, nm2))), .SDcols = nm3] Sign up to request clarification or add additional context in comments.
1 Comment
Daniel V
You've made me realise that this is probably an issue with
list -list(paste("a", "b") = 3) also fails with the same error. Thanks.Explore related questions
See similar questions with these tags.


