[datatable-help] create empty data.table

Eduard Antonyan eduard.antonyan at gmail.com
Thu Jul 23 21:32:30 CEST 2015


Perhaps smth like this:

nameToClass = data.table(name = c('Date', 'Numeric', 'Character'), class =
list(Sys.Date()[0], numeric(0), character(0)), key = 'name')

emptyDT = function(names, types) nameToClass[types,
setnames(as.data.table(class), names)]

On Thu, Jul 23, 2015 at 2:01 PM, statquant3 <statquant at outlook.com> wrote:

> My convoluted way
>
> #@usage: create empty vector
> newVec <- function(char){
>         if(char=='D') return(as.Date(integer(0)))
>         if(char=='N') return(numeric(0))
>         if(char=='C') return(character(0))
>         if(char=='I') return(integer(0))
>         return(numeric(0))
> }
>
> #@usage: create empty data.table with given types
> #@example:
> #       colNames <- c('col1','col2','col3'); colTypes <- 'DNC'; DT <-
> emptyDT(colNames,colTypes)
> emptyDT <- function(colNames,colTypes){
>         DT <- data.table(X=newVec(substr(colTypes,1L,1L)))
>         setnames(DT,'X',colNames[1L])
>         N <- length(colNames)
>         if(N>1){
>                 for(i in 2:N){
>                         DT[,X:=newVec(substr(colTypes,i,i))]
>                         setnames(DT,'X',colNames[i])
>                 }
>         }
>         return(DT)
> }
>
> R) colNames <- c('col1','col2','col3'); colTypes <- 'DNC'; DT <-
> emptyDT(colNames,colTypes)
> R) str(DT)
> Classes 'data.table' and 'data.frame':  0 obs. of  3 variables:
>  $ col1:Class 'Date'  num(0)
>  $ col2: num
>  $ col3: chr
>  - attr(*, ".internal.selfref")=<externalptr>
>
>
>
>
>
> --
> View this message in context:
> http://r.789695.n4.nabble.com/create-empty-data-table-tp4710237p4710263.html
> Sent from the datatable-help mailing list archive at Nabble.com.
> _______________________________________________
> datatable-help mailing list
> datatable-help at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/datatable-help
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/datatable-help/attachments/20150723/1b2b3679/attachment-0001.html>


More information about the datatable-help mailing list