phoxis
phoxis

Reputation: 61910

Select specific columns by string label in R frame

I want to exclude the "fldname" labeled column from a frame frm in R. If we know the index of the column say i then we can use the frm[-i] to exclude the ith column. Is there any simple way to do the same by specifying the column label string or list of label strings which i want to exclude?

I worked out a solution (corrected by Fhnuzoag):

frm[names (frm)[names (frm) != c("fldname1","fldname2")]]

frm[names (frm)[!names (frm) %in% c("fldname1","fldname2")]]

get the list of wanted strings and use them as index. Above "fldname1" and "fldname2" are the unwanted fields.

Is there a simply solution which the language syntax has?

Upvotes: 4

Views: 1938

Answers (2)

danas.zuokas
danas.zuokas

Reputation: 4643

I think, no. Usually I do frm[, setdiff(names(frm), excludelist)].

Upvotes: 1

Andrie
Andrie

Reputation: 179388

Yes, use a combination of negation ! and %in%. For example, using iris:

x <- iris[, !names(iris) %in% c("Sepal.Width", "Sepal.Length")]
str(x)
'data.frame':   150 obs. of  3 variables:
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

Upvotes: 5

Related Questions