2016-03-02 59 views
0

我想在for循環中創建新列。在for循環數據中創建新列。

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] 

我不知道到底有多少列,所以我需要用for循環來做。

+2

你見過[引用語義(https://github.com/Rdatatable/data.table/wiki/Getting-started)小插曲? – Arun

+1

謝謝,@阿倫。我找到了答案。 –

回答

2

就有答案了,即使沒有使用循環

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]