Question

I have two data frames. Data frame "weather" looks like this:

weather<-data.frame(Date=c("2012-04-01","2012-04-02","2012-04-03","2012-04-04"),Day=c("Sunday","Monday","Tuesday","Wednesday"), Temp=c(86,89,81,80))
Date       Day       Temperature    
2012-04-01 Sunday     86
2012-04-02 Monday     89
2012-04-03 Tuesday    81
2012-04-04 Wednesday  80

And, data frame "Regularity", looks like this:

Regularity<-data.frame(Date=c("2012-04-02","2012-04-04","2012-04-03","2012-04-04"),EmployeeID=c(1,1,2,2),Attendance=c(1,1,1,1))

Date        EmployeeID Attendance
2012-04-02           1          1
2012-04-04           1          1
2012-04-03           2          1
2012-04-04           2          1

I want to create a panel dataframe in R of the form:

Date       Day       Temperature EmployeeID Attendence  
2012-04-01 Sunday     86              1         0
2012-04-02 Monday     89              1         1
2012-04-03 Tuesday    81              1         0
2012-04-04 Wednesday  80              1         1
2012-04-01 Sunday     86              2         0
2012-04-02 Monday     89              2         0
2012-04-03 Tuesday    81              2         1
2012-04-04 Wednesday  80              2         1

I have tried the merge and reshape2, but in vain. I will be very grateful for any help. Thank you.

Était-ce utile?

La solution

Here is how. Suppose tb1 is the first table and tb2 is the second. Then the desired result will be achieved by following:

tb2_tf<-dcast(tb2,Date~EmployeeID,value.var="Attendance")
tb<-melt(merge(tb1,tb2_tf,all=TRUE),id=1:3,variable.name="EmployeeID",value.name="Attendance")
tb$Attendance[is.na(tb$Attendance)] <- 0
tb
       Date       Day Temperature EmployeeID Attendance
1 2012-04-01    Sunday          86          1          0
2 2012-04-02    Monday          89          1          1
3 2012-04-03   Tuesday          81          1          0
4 2012-04-04 Wednesday          80          1          1
5 2012-04-01    Sunday          86          2          0
6 2012-04-02    Monday          89          2          0
7 2012-04-03   Tuesday          81          2          1
8 2012-04-04 Wednesday          80          2          1

I would like to see the solution without the reshape part. I suspect there is one using some form of theta join.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top