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.

5
  • 4
    Could do df[df[xx] == "A", ] Commented Apr 21, 2015 at 10:58
  • 2
    Avoid using subset and use standard [ and [[ operators, like @DavidArenburg suggests. Also df[df[[xx]]=="A",] works in this case. Commented Apr 21, 2015 at 10:59
  • possible duplicate of how to extract a subset of a data frame based on a condition involving a field? Commented Apr 21, 2015 at 11:25
  • stackoverflow.com/questions/29540658/r-how-to-make-a-subtable/… just remember to put the string in quotation marks ".." Commented Apr 21, 2015 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., stackoverflow.com/questions/9860090/…). Commented Apr 21, 2015 at 12:59

1 Answer 1

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")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.