Sergio.pv
Sergio.pv

Reputation: 1400

subsetting a data frame using a vector as parameter

i have a vector conaining terms that I would like to use as parameter to subset a data frame. This is a brief example:

#this is my data frame
dat <- data.frame(x=c(1:5), y=c("a","b","c","d","e"), z=c(7,13,20,27,33)) 

#this is the vector I want to use as subsetting parameter:
w=c("c","d","e")

#and I would like to get in return all the associated columns, like this:
dat_subset <- data.frame(x=c(3:5), y=c("c","d","e"), z=c(20,27,33))

I have a very large list of terms so typing in all terms for selection is not possible.

Thanks!

Upvotes: 0

Views: 92

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193507

Perhaps you are just looking for %in%. I'm assuming that the values in "w" should come from your "y" column.

dat[dat$y %in% w, ]
#   x y  z
# 3 3 c 20
# 4 4 d 27
# 5 5 e 33

Upvotes: 1

Related Questions