[R] Adding a column to an **empty** data.frame
wdunlap at tibco.com
Wed Nov 2 14:59:01 CET 2016
Give your new column a vector type - NULL cannot be extended beyond length
0. Also, the syntax df$col<-NULL means to remove 'col' from 'df'.
> df <- data.frame(id=integer(0), data=numeric(0))
> df$new.col <- character(0)
'data.frame': 0 obs. of 3 variables:
$ id : int
$ data : num
$ new.col: chr
(Think of 'zero-row' or 'zero-column' data.frames, not 'empty' data.frames,
which could be either.)
On Wed, Nov 2, 2016 at 6:48 AM, Emmanuel Levy <emmanuel.levy at gmail.com>
> Dear All,
> This sounds simple but can't figure out a good way to do it.
> Let's say that I have an empty data frame "df":
> ## creates the df
> df = data.frame( id=1, data=2)
> ## empties the df, perhaps there is a more elegant way to create an empty
> df = df[-c(1),]
> > df
>  id data
> <0 rows> (or 0-length row.names)
> Now, how can I add a third column name to that empty df?
> Normally I would use df$new.col = 1
> But here I can't use this because it's empty!
> I tried df$new.col=NULL -- this doesn't give an error but doesn't add the
> Thanks for your help,
> [[alternative HTML version deleted]]
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> PLEASE do read the posting guide http://www.R-project.org/
> and provide commented, minimal, self-contained, reproducible code.
[[alternative HTML version deleted]]
More information about the R-help