0

may I know how to loop through the columns and use the data.table functions in R. Below is my code. Although I fulfilled all the condition (I believe so at least), there was an error. Thanks in advance.

> for (i in names(baby2.dt)) {
+     baby2.dt[is.na(i), .(.N, i := mean(baby2.dt$i, na.rm=TRUE))]
+ }
Error in `:=`(i, mean(baby2.dt$i, na.rm = TRUE)) : 
  Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").
> is.data.table(baby2.dt)
[1] TRUE
  • Did you read the error message? It tells you exactly what do to. Did you try `baby2.dt[,..i]`? Or check out [the faq](https://cran.r-project.org/web/packages/data.table/vignettes/datatable-faq.html#j-num) – MrFlick Aug 27 '20 at 02:58

1 Answers1

1

Try adding the dots (as flick says, it's what the error message suggests):

data(cars)
dt <- data.table(cars)
for (i in 1:ncol(dt)) { print(dt[,..i]) }
  • Hi, in the first case of trying to obtain the column. The (..) works. But how do you make use of the dt functions other than to obtain the column in a for loop. I edited the question to match my concern. I hope you can help me. Thank you. – Leon Cule Aug 27 '20 at 13:50