[datatable-help] := suggestions
Damian Betebenner
dbetebenner at nciea.org
Fri May 11 20:15:25 CEST 2012
All,
Trying to use := well but get errors and warnings and am looking for an elegant way to subset and use := together when multiple variables are being created and factors are involved.
Here's some code showing what I'm trying to do. Any help in doing this better greatly appreciated:
#########################################################
###
### Test of data.table and :=
###
#########################################################
require(data.table)
### Base data.table
test.dt <- data.table(ID=rep(1:10, 2), CONTENT_AREA=as.factor(rep(c("MATH", "READ"), each=10)), X=rnorm(10))
setkeyv(test.dt, c("ID", "CONTENT_AREA"))
test.dt
### Values to be looked up
my.lookup <- data.table(ID=1:5, CONTENT_AREA=as.factor("MATH"))
my.lookup
### Data table to be added to the original data.table
my.additional.table <- data.table(my.lookup, VALID_CASE=factor(1, levels=1:2, labels=c("VALID_CASE", "INVALID_CASE")), Y=as.factor(letters[1:5]), Z=101:105)
my.additional.table
### First attempt with error
test.dt[my.lookup, names(my.new.table) := my.additional.table, with=FALSE, mult="first"]
### Create the variables in test.dt using := (but gives warnings and is cumbersome to have to specify the class of the variables that are going to be created)
### NOTE:
for (i in c("VALID_CASE", "Y", "Z")) {
test.dt[, i := NA_integer_, with=FALSE, mult="first"]
class(test.dt[[i]]) <- class(my.additional.table[[i]])
if (is.factor(test.dt[[i]])) levels(test.dt[[i]]) <- levels(my.additional.table[[i]])
}
### Sucessfully perform the variable creation on the rows indicated by my.lookup
test.dt[my.lookup, names(my.additional.table) := my.additional.table, with=FALSE, mult="first"]
Damian Betebenner
Center for Assessment
PO Box 351
Dover, NH 03821-0351
Phone (office): (603) 516-7900
Phone (cell): (857) 234-2474
Fax: (603) 516-7910
dbetebenner at nciea.org<mailto:dbetebenner at nciea.org>
www.nciea.org<http://www.nciea.org/>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20120511/2e425108/attachment.html>
More information about the datatable-help
mailing list