[R] Adding a column to an **empty** data.frame
emmanuel.levy at gmail.com
Wed Nov 2 15:07:06 CET 2016
Thanks a lot this is what I was looking for.
On 2 November 2016 at 15:59, William Dunlap <wdunlap at tibco.com> wrote:
> 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)
> > str(df)
> '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.)
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
> 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/posti
>> and provide commented, minimal, self-contained, reproducible code.
[[alternative HTML version deleted]]
More information about the R-help