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

前端 未结 5 1223
暗喜
暗喜 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:19

    Another option:

    library(dplyr)
    library(tidyr)
    Inc %>%
      gather(eth, value, -ZIP2) %>%
      left_join(df, ., by = c("eth", "ZIP1" = "ZIP2"))
    
    0 讨论(0)
  • 2021-01-18 02:20

    my solution(which maybe seems awkward)

    for (i in 1:length(df$eth)) {
        df$Inc[i] <- Inc[as.character(df$eth[i])][df$ZIP[i],]
    }
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-18 02:26

    Sure, it can be done in data.table:

    library(data.table)
    setDT(df)
    
    df[ melt(Inc, id.var="ZIP2", variable.name="eth", value.name="Inc"), 
      Inc := i.Inc
    , on=c(ZIP1 = "ZIP2","eth") ]
    

    The syntax for this "merge-assign" operation is X[i, Xcol := expression, on=merge_cols].

    You can run the i = melt(Inc, id.var="ZIP", variable.name="eth", value.name="Inc") part on its own to see how it works. Inside the merge, columns from i can be referred to with i.* prefixes.


    Alternately...

    setDT(df)
    setDT(Inc)
    df[, Inc := Inc[.(ZIP1), eth, on="ZIP2", with=FALSE], by=eth]
    

    This is built on a similar idea. The package vignettes are a good place to start for this sort of syntax.

    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题