R - Create a new variable where each observation depends on another table and other variables in the data frame

前端 未结 5 1217
暗喜
暗喜 2021-01-18 02:06

I have the two following tables:

df <- data.frame(eth = c(\"A\",\"B\",\"B\",\"A\",\"C\"),ZIP1 = c(1,1,2,3,5))
Inc <- data.frame(ZIP2 = c(1,2,3,4,5,6,7)         


        
5条回答
  •  -上瘾入骨i
    2021-01-18 02:29

    We can use row/column indexing

    df$Inc <- Inc[cbind(match(df$ZIP1, Inc$ZIP2), match(df$eth, colnames(Inc)))]
    
    df
    #  eth ZIP1 Inc
    #1   A    1  56
    #2   B    1  49
    #3   B    2  10
    #4   A    3  43
    #5   C    5  17
    

提交回复
热议问题