Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
775 views
in Technique[技术] by (71.8m points)

r - subsetting data frame based on search pattern in vector

I've spent a few hours on a problem with subsetting data frame rows based on search pattern in a vector. I'm newbie in R. Maybe it's easy, but I can't do it myself, and I can't find a solution in stackoverflow

Suppose that I've a mtcars data from R.

I want to subset rows with a few cars name for example only Mazda, Ford and Chevrolet. So I have a character vector car.names with names of cars I want to subset:

car.names <- c("Mazda", "Ford", "Chevrolet")

Question is: How to subset mtcars rows based on criteria in car.names?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think you are wanting to combine a grep search with indexing. Here's I would approach it for mtcars:

car.names <- "Mazda|Ford|Chevrolet"
filtered <- mtcars[grepl(car.names, rownames(mtcars)),]
filtered
#                mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4      21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag  21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# Ford Pantera L 15.8   8  351 264 4.22 3.170 14.50  0  1    5    4

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...