1

I'm trying to simplify a script I'm using to extract specific rows and columns out of a large data frame and into a separate one so I can then plot a graph. Up until now I've been using a for loop to get bits out at a time and then rbind() them together, but I figure there has to be a better solution. Hopefully I can illustrate what I've been trying to do by way of a representative example:

a <- rep(1:8, each=40)
b <- rep(rep(1:4, each=5), times=16)
c <- runif(320)
d <- runif(320)

df <- data.frame(a,b,c,d)

What I'd like to do is get these columns out for specific values of a and b. So I figured, for example to get out the rows where a is 1 or 2, I could do so with something like:

extract.a = c(1,2)
extractcolumns = c("a", "b", "c", "d")
extracted <- df[a == extract.a, extractcolumns]

(I've left in the extractcolumns bit even though I don't need it in this case, but in the real case I want to take 5 columns out of 17). Problem is this sort-of-works but takes only every other row, and if I change, for example,

extract.a = c(1,2,4)

Then it takes every third row. I'm not sure exactly what it's doing here so I'm stuck on how to fix it. What I would ultimately like to do is select rows where a is one of several values and b is also one of two values. Something like:

 extract.b = c(1,4)
 extracted <- df[a == extract.a & b == extract.b, extractcolumns]

...but obviously this isn't right either. This works, for example:

 extracted <- df[(a == 1 | a == 2 | a == 4) & (b == 1 | b == 3), extractcolumns]

But I would like to be able to define the values for a and b I would like somewhere else as I've done above.

I hope that's clear enough!

1
  • df[a %in% extract.a & b %in% extract.b, extractcolumns] ? Commented Mar 11, 2015 at 20:59

1 Answer 1

1

The solution is to use the %in% operator instead of == which can perform a multiple comparison

df[a %in% extract.a & b %in% extract.b, extractcolumns]
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.