简体   繁体   中英

R: extracting specific rows and columns from dataframe

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!

解决方案是使用%in%运算符而不是==来执行多重比较

df[a %in% extract.a & b %in% extract.b, extractcolumns]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM