How can I use one column to determine where I get the value for another column?

前端 未结 3 1983
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 15:33

I\'m trying to use one column to determine which column to use as the value for another column It looks something like this:

     X   Y  Z   Target
1    a   b           


        
3条回答
  •  时光说笑
    2021-01-25 16:07

    library(tidyverse)
    
    df <-setNames(data.frame(cbind(matrix(letters[1:9],3,3,byrow=T), c("X", "Y", "Z"))), c("X", "Y", "Z", "Target"))
    
    df
    
    df %>% 
      gather(key="ID", value="TargetValue", X:Z) %>%
      filter(ID==Target) %>%
      select(Target, TargetValue) %>%
      left_join(df, by="Target")
    

提交回复
热议问题