4

I have a data frame in R like this:

> df <- data.frame(cbind(C.01=1, C.02=1:8, C.03=c("A","B","C","D","E","F","G","H")))

And I would obtain a subset like this:

> subset(df, C.03 == "A")

C.01 C.02 C.03
1    1    1    A

It's possible do the same subset but having the name of the column in xx <- "C.03" ??

Because subset(df, xx == "A") doesn't works.

Thnks.

user2820398
  • 63
  • 1
  • 1
  • 5
  • 4
    Could do `df[df[xx] == "A", ]` – David Arenburg Apr 21 '15 at 10:58
  • 2
    Avoid using `subset` and use standard `[` and `[[` operators, like @DavidArenburg suggests. Also `df[df[[xx]]=="A",]` works in this case. – nicola Apr 21 '15 at 10:59
  • possible duplicate of [how to extract a subset of a data frame based on a condition involving a field?](http://stackoverflow.com/questions/3445590/how-to-extract-a-subset-of-a-data-frame-based-on-a-condition-involving-a-field) – rmuc8 Apr 21 '15 at 11:25
  • http://stackoverflow.com/questions/29540658/r-how-to-make-a-subtable/29541508#29541508 just remember to put the string in quotation marks `".."` – rmuc8 Apr 21 '15 at 11:27
  • 1
    I would strongly advise to use either David's or nicola's solution but, if you really want to use `subset`, you could try `subset(df,eval(parse(text=paste0(xx,"==","\"A\""))))`. However, this kind of hacky code ultimately eliminates `subset`'s main advantage of better readability. Using `subset` might also cause unexpected behaviour (see, e.g., http://stackoverflow.com/questions/9860090/in-r-why-is-better-than-subset). – cryo111 Apr 21 '15 at 12:59

1 Answers1

3

Using base R (thanks @David Arenburg):

df[df[xx] == "A", ]

Or with dplyr, which I suggest because the syntax is easier to make sense of:

require("dplyr")
df <- filter(df, C.03 == "A")
Phil
  • 4,344
  • 2
  • 23
  • 33