简体   繁体   中英

Select row which matched to the words from another dataframe (R)

I'm a bit confused about the keyword to search this problem. Could you help me or give me any suggestion to solve this problem in R

I have the dataframe A like this

list_fruit
<chr>
Orange
Grape
Watermelon
Mango

and I want to bring this dataframe match with another dataset B

This is dataset B

Fruit      Number    Price
<chr>      <int>     <int>
Banana      56        25
Watermelon  5         100
Pineapple   96        150
Guava       47        20
Orange      3         120

so the rows of 'Watermelon' and 'Orange' will be selected and were collected in new dataframe

Fruit      Number    Price
<chr>      <int>     <int>
Watermelon  5         100
Orange      3         120

Thank you in advanced

I think you are looking for inner_join . Let's call your first data frame df1 and the second df2. Then:

library(tidyverse)
df1 %>% 
  inner_join(df2, by = c("list_fruit" = "Fruit"))
#>   list_fruit Number Price
#> 1     Orange      3   120
#> 2 Watermelon      5   100

Created on 2022-01-27 by the reprex package (v2.0.1)

From the help page:

inner_join(): includes all rows in x and y.

Here, this means you match the columns by list_fruit in df1 and Fruit in df 2. You join the data frame by adding the columns from df2 to the right of df1. And you only keep rows where you get a match.

data using dput()

df1 <- structure(list(list_fruit = c("Orange", "Grape", "Watermelon", 
                                     "Mango")), class = "data.frame", row.names = c(NA, -4L))

df2 <- structure(list(Fruit = c("Banana", "Watermelon", "Pineapple", 
                                "Guava", "Orange"), Number = c(56L, 5L, 96L, 47L, 3L), Price = c(25L, 
                                                                                                 100L, 150L, 20L, 120L)), class = "data.frame", row.names = c(NA, 
                                                                                                                                                              -5L))

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