Search code examples
rdplyrplyrreshape2

Index - Match using dplyr in R


Here it is mydata:

datex <- c(rep("2021-07-01", 9), rep("2021-07-02", 9))
hourx <- rep(rep(0:2),6)
seller <- c("Se1","Se1","Se1","Se2","Se2","Se2","Se2","Se2","Se2","Se1","Se1","Se1","Se2","Se2","Se2","Se2","Se2","Se2")
product <- c("Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1","Pro1")
detail <- c("De1","De1","De1","De1","De1","De1","De1","De1","De1","De1","De1","De1","De1","De1","De1","De1","De1","De1")
status <- c("St1","St1","St1","St1","St1","St1","St1","St1","St1","St1","St1","St1","St1","St1","St1","St1","St1","St1")
channel <- c("Ch1","Ch1","Ch1","Ch1","Ch1","Ch1","Ch2","Ch2","Ch2","Ch1","Ch1","Ch1","Ch1","Ch1","Ch1","Ch2","Ch2","Ch2")
transaction <- c(16,29,45,23,41,45,47,38,23,39,43,35,10,43,20,43,28,38)
mydata <- data.frame(datex, hourx, seller, product, detail, status, channel, transaction)

I want to fill hourx for this mydata.result table, it contains NA value.

datex <- c(rep("2021-07-01", 2), rep("2021-07-02", 2))
hourx <- c(NA, NA, NA, NA)
seller <- c("Se1","Se2","Se1","Se2")
product <- c("Pro1","Pro1","Pro1","Pro1")
detail <- c("De1","De1","De1","De1")
status <- c("St1","St1","St1","St1")
channel <- c("Ch1","Ch1","Ch1","Ch2")
transaction <- c(16,41,35,28)
mydata.result <- data.frame(datex, hourx, seller, product, detail, status, channel, transaction)

How do i fill hourx from "mydata" into "mydata.result"? It's like Index-Match in Excel, but i need it in R. Thanks.


Solution

  • If I understood, you want to join the data.frames

    mydata.result %>% 
      #remove hourx from mydata.result  
      select(-hourx) %>% 
      #join with mydata  
      left_join(mydata)
    

    -output

    Joining,
     by = c("datex", "seller", "product", "detail", "status", "channel", "transaction")
    
    
           datex seller product detail status channel transaction hourx
    1 2021-07-01    Se1    Pro1    De1    St1     Ch1          16     0
    2 2021-07-01    Se2    Pro1    De1    St1     Ch1          41     1
    3 2021-07-02    Se1    Pro1    De1    St1     Ch1          35     2
    4 2021-07-02    Se2    Pro1    De1    St1     Ch2          28     1