0

I have two data frames in R:

df1 <- data.frame("name" = c("jack", "william", "david", "john", "peter", "aaron"), 
                 "city" = c("LA","HK","NY","TK", "PARIS","SYDNEY"))
df2 <- data.frame("name" = c("jack", "william", "david", "john", "peter", "aaron", "jack", "william", 
                           "david", "john"),
                  "fruit" = c("apple", "pear", "kiwi", "peach", "avocado", "orange", "pineapple", "pear", 
                           "watermelon", "rockmelon"))

I want to pick up all the "fruit" information for everyone (from df2), then add to df1, so I use this:

match <- match(df1$name, df2$name)
df1$fruit=df2$fruit(match) 

I get "Error: attempt to apply non-function". how do I overcome the fact that one person may have multiple fruits in df2?

Many thanks!

Almond
  • 87
  • 1
  • 1
  • 5

1 Answers1

0

If you don't mind using dplyr, you can easily achieve what you want using left_join():

library(dplyr)

df1 %>%
   left_join(df2, by = 'name')

(joins are generally very useful, I recommend learning them, it can really make your workflow a lot more efficient)

Adam B.
  • 788
  • 5
  • 14