3

I have a (big-ish) data.table. And I want to do the same thing to many of its columns. Say,

dt <- data.table( ltr = letters[1:5] )
func <- function( dt ){
    cols <- colnames( dt ) # Columns to apply op to
    dt[ , (cols) := lapply( .SD, toupper ), .SDcols = cols ]
    return( dt )
}

The function func converts characters to upper case for all columns. I try

func( dt )

I get the error

Error in `:=`((cols), lapply(.SD, toupper)) : 
Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").

I'm still not sure what causes the error and have read help(":="), the FAQs and some other (SO) sources. Any help?

NOTE: I should have given more details about the context. func is a function written in a package. That makes all the difference

vathymut
  • 1,017
  • 2
  • 13
  • 25
  • 1
    I'm not getting any error neither. Though, you need to be aware that your `dt` in the global environment is being updated by reference using `:=`. So no need in `return( dt )`. I would also suggest to explore `set` as it suites better for such operations. – David Arenburg Jun 02 '15 at 16:20
  • 2
    Are you using this function from within a package? If so, [make sure your package is data.table aware](http://stackoverflow.com/a/10529888/559784).. – Arun Jun 02 '15 at 16:25
  • Option 2 seems to do the trick. I used roxygen2 for docs. `data.table` is listed in the `Imports` fields in DESCRIPTION but `import(data.table)` does not show up in NAMESPACE. Sad thing is I read and upvoted that answer :( Thanks, @Arun. If you make that an answer, I'll accept it. – vathymut Jun 02 '15 at 16:40
  • Glad it's resolved. You can answer it yourself, and accept it. – Arun Jun 02 '15 at 16:41
  • 1
    (@DavidArenburg :) Okay: back it goes.) The last line of this answer (suggested by Arun) illustrates the usage of `set` David mentioned: http://stackoverflow.com/a/16846530/1191259 – Frank Jun 02 '15 at 17:48

1 Answers1

1

The short answer is to make sure the package is data.table aware. See @Arun's comment.

Note that using devtools::use_package( "data.table", pkg = "." ) will add to the Imports field in DESCRIPTION but not explicitly import( data.table ) in NAMESPACE. As such, including data.table in the Depends field -- that's the first option Matthew outlines in his post -- may be more foolproof.

Community
  • 1
  • 1
vathymut
  • 1,017
  • 2
  • 13
  • 25