0

is it possible to filter rows of one dataframe based on another dataframe?

I have this 2 dataframe:

df_node <- data.frame( id= c("a","b","c","d","e","f","g","h","i"),
                   group= c(1,1,1,2,2,2,3,3,3))

df_link <- data.frame(from = c("a","d","f","i","b"),
                     to =   c("d","f","i","b","h"))

enter image description here

I would like to delete the lines with characters that are not present in the second dataframe, like this:

enter image description here

1
  • 1
    Please do not post images of codes or data. If you want to show the dataframe you can post a table. Commented Nov 24, 2022 at 15:35

3 Answers 3

2

here is a basic way to do that:

df_node <- data.frame( id= c("a","b","c","d","e","f","g","h","i"),
                       group= c(1,1,1,2,2,2,3,3,3))

df_link <- data.frame(from = c("a","d","f","i","b"),
                      to =   c("d","f","i","b","h"))


library(dplyr)
df_result <- df_node%>%
       filter(id%in%c(df_link$from,df_link$to))
df_result
# > df_result
# id group
# 1  a     1
# 2  b     1
# 3  d     2
# 4  f     2
# 5  h     3
# 6  i     3
Sign up to request clarification or add additional context in comments.

Comments

1

We could use a semi_join:

library(dplyr)

df_node |> 
  semi_join(tibble(id = c(df_link$from, df_link$to)))

Output:

  id group
1  a     1
2  b     1
3  d     2
4  f     2
5  h     3
6  i     3

Comments

1

Here is a oneliner with base R:

df_node[df_node$id %in% unlist(df_link),]

  id group
1  a     1
2  b     1
4  d     2
6  f     2
8  h     3
9  i     3

But you could also use a join:

library(dplyr)

df_uniqueID <- data.frame(id = unique(c(df_link$from,df_link$to)) )
right_join(df_node,df_uniqueID)

Joining, by = "id"
  id group
1  a     1
2  b     1
3  d     2
4  f     2
5  h     3
6  i     3

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.