Lookup values in a vectorized way

前端 未结 1 1226
一个人的身影
一个人的身影 2021-01-18 14:34

I keep reading about the importance of vectorized functionality so hopefully someone can help me out here.

Say I have a data frame with two columns: name

相关标签:
1条回答
  • 2021-01-18 15:16

    See ?merge which will perform a database link merge or join.

    Here is an example:

    set.seed(2)
    d1 <- data.frame(ID = 1:5, Name = c("Bill","Bob","Jessica","Jennifer","Robyn"))
    d2 <- data.frame(Name = c("Bill", "Gavin", "Bob", "Joris", "Jessica", "Andrie", 
                              "Jennifer","Joshua","Robyn","Iterator"),
                     Birthplace = sample(c("London","New York",
                                           "San Francisco", "Berlin",
                                           "Tokyo", "Paris"), 10, rep = TRUE))
    

    which gives:

    > d1
      ID     Name
    1  1     Bill
    2  2      Bob
    3  3  Jessica
    4  4 Jennifer
    5  5    Robyn
    > d2
           Name    Birthplace
    1      Bill      New York
    2     Gavin         Tokyo
    3       Bob        Berlin
    4     Joris      New York
    5   Jessica         Paris
    6    Andrie         Paris
    7  Jennifer        London
    8    Joshua         Paris
    9     Robyn San Francisco
    10 Iterator        Berlin
    

    Then we use merge() to do the join:

    > merge(d1, d2)
          Name ID    Birthplace
    1     Bill  1      New York
    2      Bob  2        Berlin
    3 Jennifer  4        London
    4  Jessica  3         Paris
    5    Robyn  5 San Francisco
    
    0 讨论(0)
提交回复
热议问题