1

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?

askedDec 11, 2020 at 23:05
Daniel V's user avatar
0

1 Answer1

4

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]
answeredDec 11, 2020 at 23:08
akrun's user avatar
Sign up to request clarification or add additional context in comments.

1 Comment

You've made me realise that this is probably an issue withlist -list(paste("a", "b") = 3) also fails with the same error. Thanks.

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.