Inner Join with conditions in R

后端 未结 3 942
野的像风
野的像风 2021-01-20 07:37

I want to do inner join with the condition that it should give me subtraction of 2 columns.

df1 = data.frame(Term = c(\"T1\",\"T2\",\"T3\"), Sec = c(\         


        
相关标签:
3条回答
  • 2021-01-20 07:43

    As this is a dplyr question, here is a dplyr solution :

    First use inner_join and then transmute to keep variables and compute and append a new one.

    inner_join(df1, df2, by = "Sec") %>% 
      transmute(Term = Term.x, Sec, Value = abs(Value.x - Value.y))
    
    0 讨论(0)
  • 2021-01-20 07:58

    Here is a "base R" solution using the merge() function on the Term column shared by your original df1 and df2 data frames:

    df_merged <- merge(df1, df2, by="Sec")
    df_merged$Value <- abs(df_merged$Value.x - df_merged$Value.y)
    df_merged <- df_merged[, c("Sec", "Term.x", "Value")]
    names(df_merged)[2] <- "Term"
    
    > df_merged
      Sec Term Value
    1  s1   T1    30
    2  s2   T2    20
    3  s3   T3    10
    
    0 讨论(0)
  • 2021-01-20 07:59

    Using data.tables binary join you can modify columns while joining. nomatch = 0L makes sure that you are doing an inner join

    library(data.table)
    setkey(setDT(df2), Sec)
    setkey(setDT(df1), Sec)[df2, .(Term, Sec, Value = abs(Value - i.Value)), nomatch = 0L]
    #    Term Sec Value
    # 1:   T1  s1    30
    # 2:   T2  s2    20
    # 3:   T3  s3    10
    
    0 讨论(0)
提交回复
热议问题