[R] how to NULL multiple variables of a df efficiently?

Christos Hatzis christos.hatzis at nuverabio.com
Tue Feb 24 23:00:11 CET 2009

You're right.  The help page is somewhat misleading at first read.

?`[<-.data.frame` states that (with added emphasis)

value 	A suitable replacement value: it will be repeated a whole number of
times if necessary and it may be coerced: see the Coercion section. *** If
NULL, deletes the column if a single column is selected. ***
So I read this to mean that a NULL value works only if a single column is
But the Details gives the rest of the story:

For [ the replacement value can be a list: each element of the list is used
to replace (part of) one column, recycling the list as necessary. If columns
specified by number are created, the names (if any) of the corresponding
list elements are used to name the columns. *** If the replacement is not
selecting rows, list values can contain NULL elements which will cause the
corresponding columns to be deleted. ***


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Stavros Macrakis
> Sent: Tuesday, February 24, 2009 4:47 PM
> To: Sean Zhang
> Cc: r-help at r-project.org
> Subject: Re: [R] how to NULL multiple variables of a df efficiently?
> On Tue, Feb 24, 2009 at  3:10 PM, Sean Zhang wrote:
> > ...Want to delete many variables in a dataframe....
> > df<-data.frame(var.a=rnorm(10), var.b=rnorm(10),var.c=rnorm(10))
> > df[,'var.a']<-NULL   #this works for one single variable
> > df[,c('var.a','var.b')]<-NULL  #does not work for multiple variables
> Actually, setting to NULL works fine for multiple variables, 
> but you need one NULL per variable:
> > df[,c("var.a","var.b")] <- list(NULL,NULL) df
>         var.c
> 1   1.2470314
> 2  -0.7075917
> 3  -1.3959612
> If the variable list is in a variable:
> > vars <- c("var.a","var.c")
> Careful, rep requires a *list* of NULL, not an element:
> > df[,vars] <- rep(list(NULL),length(vars))
> Hope this helps,
>              -s
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list