0

I want to create new columns in for loop.

impute.sum <- function(x) replace(x, is.na(x), -sum(x, na.rm = TRUE))
df = data.table(user = c(1,1,2,2,3,3,3), x1 = c(NA, 2, 4, NA, NA, 1, 1), x2 = c(1, NA, NA, 3, 4, NA, NA))
df[, x1_1 := impute.sum(x1), by = user]
df[, x2_1 := impute.sum(x2), by = user]

I don't know exactly how many columns I will have, so I need to do it with for loop.

2
  • 2
    Have you seen the reference semantics vignette? Commented Mar 2, 2016 at 10:21
  • 1
    Thanks, @Arun. I've found the answer. Commented Mar 2, 2016 at 10:27

1 Answer 1

2

There is the answer even without using for loop

impute.sum <- function(x) replace(x, is.na(x), -sum(x, na.rm = TRUE))
df = data.table(user = c(1,1,2,2,3,3,3), x1 = c(NA, 2, 4, NA, NA, 1, 1), x2 = c(1, NA, NA, 3, 4, NA, NA))
in_cols  = c("x1", "x2")
out_cols = c("x1_1", "x2_1")
df[, c(out_cols) := lapply(.SD, impute.sum), by = user, .SDcols = in_cols]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy 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.