PradeepLR PradeepLR -4 years ago 98
R Question

subsetting using column names as objects

I am trying to subset a data frame using a column names stored in an object. Is this possible? Here is an example:

ReallyLongColNameA <- c(1,2,3,4,5,6)

ReallyLongColNameB <- c(6,5,4,3,2,1)

ReallyLongColNameC <- c(7,8,9,10,11,12)

X <- data.frame(ReallyLongColNameA, ReallyLongColNameB, ReallyLongColNameC)

can i store a column name as such:
ShortColNameB <- names(X[2])
and then subset using the column name stored in object ShortColNameB

I can subset the following:
subX <- X[X$ReallyLongColB == 6,]

To get:

ReallyLongColA ReallyLongColB ReallyLongColC
1 6 7

But what if I wanted the following desired output by using the column name stored in an object (ShortColNameB)?:

ReallyLongColA ReallyLongColB
1 6

Thanks for your help in advance.

Answer Source

You can easily remove the last column by subsetting on column numbers.


You define what rows you want by filtering on the ==6 for ShortColNameB, and you define the columns you want by selecting the numbers (e.g. 1st and 2nd column, A & B).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download