List all column except for one in R

RDataframe

R Problem Overview


> Possible Duplicate:
> Drop Columns R Data frame

Let's say I have a dataframe with column c1, c2, c3.

I want to list just c1 and c2. How do I do that?

I've tried:

head(data[column!="c3"])
head(data)[,2]
head(data[!"c3"])

R Solutions


Solution 1 - R

If you are looking for negative indexing by name (in addition to tcash21's numeric indexing), here's a few ways I know, some riskier than others:

mtcars[, -which(names(mtcars) == "carb")]  #only works on a single column
mtcars[, names(mtcars) != "carb"]          #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")] 
mtcars[, -match(c("carb", "mpg"), names(mtcars))] 
mtcars2 <- mtcars; mtcars2$hp <- NULL         #lost column (risky)


library(gdata) 
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE) 

Generally I use:

mtcars[, !names(mtcars) %in% c("carb", "mpg")] 

because I feel it's safe and efficient.

Solution 2 - R

You can index and use a negative sign to drop the 3rd column:

data[,-3]

Or you can list only the first 2 columns:

data[,c("c1", "c2")]
data[,1:2]

Don't forget the comma and referencing data frames works like this: data[row,column]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmythicalprogrammerView Question on Stackoverflow
Solution 1 - RTyler RinkerView Answer on Stackoverflow
Solution 2 - Rtcash21View Answer on Stackoverflow