Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select specific columns by string label in R frame

Tags:

dataframe

r

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?

like image 998
phoxis Avatar asked Oct 15 '25 07:10

phoxis


2 Answers

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 ...
like image 89
Andrie Avatar answered Oct 18 '25 04:10

Andrie


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

like image 45
danas.zuokas Avatar answered Oct 18 '25 05:10

danas.zuokas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!