繁体   English   中英

Select 行与另一个 dataframe (R) 中的单词匹配

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

我对搜索这个问题的关键字有点困惑。 你能帮我或给我任何建议来解决 R 中的这个问题吗

我有这样的 dataframe A

list_fruit
<chr>
Orange
Grape
Watermelon
Mango

我想把这个 dataframe 与另一个数据集 B 匹配

这是数据集 B

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

因此将选择“西瓜”和“橙色”的行并将其收集到新的 dataframe

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

谢谢先进

我认为您正在寻找inner_join 我们将您的第一个数据框称为 df1 和第二个 df2。 然后:

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

代表 package (v2.0.1) 于 2022 年 1 月 27 日创建

从帮助页面:

inner_join():包括 x 和 y 中的所有行。

在这里,这意味着您通过 df1 中的list_fruit和 df 2 中的Fruit匹配列。您通过将 df2 中的列添加到 df1 的右侧来加入数据框。 而且你只保留你得到匹配的行。

使用 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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM