如何在2个数据帧之间进行查找

时间:2018-06-27 13:47:08

标签: r dataframe

这是我的数据集:

type <- c("apple","orange","banana","others")
price <- c(10,9,8,7)
shop <- data.frame(type,price)

fruit <- c("apple","orange","banana","mango","lemon")
buy <- data.frame(fruit)

shop
    type price
1  apple    10
2 orange     9
3 banana     8
4 others     7

buy
   fruit
1  apple
2 orange
3 banana
4  mango
5  lemon

我如何得到这样的结果?

   fruit   type price
1  apple  apple    10
2 orange orange     9
3 banana banana     8
4  mango others     7
5  lemon others     7

我尝试使用合并或联接,但是芒果和柠檬不在data.frame shop中,它仅返回NA。 我想确定不是“类型”的水果,全部归还给他人,价格为7。

1 个答案:

答案 0 :(得分:3)

使用dplyr的解决方案。注意,我更改了创建示例数据框的方式,因为我不希望将列作为因素。 stringsAsFactors = FALSE使它们成为字符。

library(dplyr)

# Find out what are "others".
others <- fruit[!fruit %in% type]

dat <- buy %>%
  mutate(type = ifelse(fruit %in% others, "others", fruit)) %>%
  left_join(shop, by = "type")
dat
#    fruit   type price
# 1  apple  apple    10
# 2 orange orange     9
# 3 banana banana     8
# 4  mango others     7
# 5  lemon others     7

数据

type <- c("apple","orange","banana","others")
price <- c(10,9,8,7)
shop <- data.frame(type,price, stringsAsFactors = FALSE)

fruit <- c("apple","orange","banana","mango","lemon")
buy <- data.frame(fruit, stringsAsFactors = FALSE)