-1

Let's say I have two data frame A and B.

A

 products    price
   apple      3.0
   orange     2.5
   avocado    4.0
   banana     2.5
   blueberry  1.5

B

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

My question is what is the fastest way to grep the product prices from data A and save it in data B, so the result will be like this

B

products Color  price
  banana   Yellow  2.5
  Apple    Red     3.0
  Avocado  Green   4.0
  Apricot  Yellow  NA
Fouad Selmane
  • 378
  • 2
  • 11

1 Answers1

1

If the only difference between the products in B and A is the capitalization then you could use the following:

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)]
}
Areeb
  • 11
  • 1