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

前端 未结 5 1215
暗喜
暗喜 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条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-18 02:22

    What about this?

    library(reshape2)
    merge(df, melt(Inc, id="ZIP2"), by.x = c("ZIP1", "eth"), by.y = c("ZIP2", "variable"))
      ZIP1 eth value
    1    1   A    56
    2    1   B    49
    3    2   B    10
    4    3   A    43
    5    5   C    17
    

提交回复
热议问题