0

I have a dataframe:

id  <- c(1:5)
name <- c("blackdog","whitedog", "blackcat","whitecat","greyrabbit")
df <- data.frame(id,name)
df

I also have a list for selection:

select <- c("black","dog","grey")

So I want to return a dataframe containing: blackdog, blackcat,whitedog,greyrabbit

I have tried:

dfselect <-df[grep(select,df[,2]),]
dfselect 

but this is only selecting the first element of the list.

I would be grateful for your help.

2 Answers 2

2

No need to use a loop here:

df[grep(paste(select,collapse='|'),df$name),]

## id       name
## 1  1   blackdog
## 2  2   whitedog
## 3  3   blackcat
## 5  5 greyrabbit
Sign up to request clarification or add additional context in comments.

1 Comment

+1 - My first thought was to insert "|" in the list but I couldn't get it to work easily. What I missed was "collapse". Thanks!
0

I think what you want to do is use the apply functions:

> df$name[unique(unlist(lapply(select, FUN=function(x) grep(x,df$name))))]
[1] blackdog   blackcat   whitedog   greyrabbit
Levels: blackcat blackdog greyrabbit whitecat whitedog

Is that what you were after?

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.