[R] alternative to subset(dataframe, select = - column) in R

Jeff Newmiller jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Fri Sep 24 16:43:27 CEST 2021

The subset function

subset( new, select = -ID )

uses non-standard evaluation... it "knows" that when you write the language symbol ID it may match to one of the column names in new, and the `-` in the select argument will be noticed before R tries to change the sign of a variable ID in your calling environment and cause subset to remove the "ID" column from the returned version of new.

The vector indexing operator does none of that, so whatever indexing arguments you specify need to be valid expressions on their own without the indexing operator.

   You don't have a variable called ID, so its sign vanity be changed

   Changing the sign of a character literal is not a defined operation

   Standalone brackets have no meaning in R... only can be used directly adjacent to a vector to the right.

What you do have is the data frame `new`... and it has names, and among those names is "ID", so...

"ID" != names( new )
   should be a logical vector with FALSE in the position corresponding to "ID", so

new[ , "ID" != names( new ) ]

will select all of the columns other than the "ID" column.

If you want to deselect more than one column, then the %in% operator can help:

! names( new ) %in% c( "ID", "Other" )

will be a logical vector with FALSE in the corresponding positions.

On September 24, 2021 7:09:54 AM PDT, Luigi Marongiu <marongiu.luigi using gmail.com> wrote:
>this is a very simple question but...
>what is the vector alternative to `subset(dataframe, select = - column)`?
>I tried with:
>> x = new[-ID]
>Error in `[.data.frame`(new, -ID) : object 'ID' not found
>> x = new[-"ID"]
>Error in -"ID" : invalid argument to unary operator
>> x = new[[-"ID"]]
>Error in -"ID" : invalid argument to unary operator
>> x = new[-["ID"]]
>Error: unexpected '[' in "x = new[-["
>Thank you
>R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.

Sent from my phone. Please excuse my brevity.

More information about the R-help mailing list