如何将完全匹配从数据B复制到r中的数据A.

时间:2017-12-14 03:21:44

标签: r dataframe dplyr stringr stringi

假设我有两个数据框A和B.

A

 products Color  price
 banana   Yellow  NA
 Apple    Red     NA
 Avocado  Green   NA
 Apricot  Yellow  NA

products Color  price
  banana   Yellow  2.5
  Apple    Red     3.0
  Avocado  Green   4.0
  Apricot  Yellow  NA

我的问题是从数据A中获取产品价格的最快方法是什么,并将其保存在数据B中,因此结果将是这样的

viewWillAppear

1 个答案:

答案 0 :(得分:1)

如果B和A中的产品之间的唯一区别是大写,那么您可以使用以下内容:

A = data.frame(products = c("apple", "orange", "avocado", "banana", "blueberry"),
           price = c(3.0, 2.5, 4.0, 2.5, 1.5))

B = data.frame(products = c("banana", "Apple", "Avocado", "Apricot"),
           color = c("Yellow", "Red", "Green", "Yellow"),
           price = c(NA, NA, NA, NA))

for (i in 1:nrow(B)) {
   B$price[i] =  A$price[match(tolower(B$products[i]), A$products)]
}