I encountered the following problem after upgrading to the latest version 1.8.1 of data.table (available on R-forge). Up to that version, I could do this:
DT = data.table(a=LETTERS[c(1,1:3)],b=4:7,key="a")
DT
a b
1: A 4
2: A 5
3: B 6
4: C 7
DT[ ,newcol := NA]
i.e. I was able to add a new column filled with NAs. Now I get an error saying that the logical type of NA is not supported (in fact DT[ ,newcol := TRUE] doesn't work either).
So right now I work around that by first adding an double column, and then setting that to NA or whatever logical I need:
DT[ ,newcol:=1]
a b newcol
1: A 4 1
2: A 5 1
3: B 6 1
4: C 7 1
and
DT[ ,newcol:=NA]
a b newcol
1: A 4 NA
2: A 5 NA
3: B 6 NA
4: C 7 NA
I wanted to ask whether this is the right way to do this. It's not a big deal I guess. It's working fine like that, just wanted to avoid unnecessary steps.
Until this bug is fixed (see Matthew Dowle's comment above), you can get around it by directly specifying the type of NA that you want in the new column (except of course for "logical", which is the type that doesn't work at the moment):
DT <- data.table(a=LETTERS[c(1,1:3)],b=4:7,key="a")
DT[ ,newcol := NA_real_] ## Other options are NA_integer_ and NA_character_
# a b newcol
# 1: A 4 NA
# 2: A 5 NA
# 3: B 6 NA
# 4: C 7 NA
## Plain old NA has type and class "logical", partly explaining the
## error message returned by DT[,newcol:=NA]
c(typeof(NA), class(NA))
# [1] "logical" "logical"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With