Reputation: 1289
I have 2 data frames with identical dimensions A,B. First column of each data frame is a date. I would like to create a 3rd data frame that has 0s where A < B and 1s where A > B where the comparison is done element wise excluding the date column. This is what I have done so far which works without looping.
C = A
C[] = 0
temp = unlist(as.relistable(as.matrix(C[-1])))
temp[which(A[-1]>B[-1])] = 1
C = data.frame(C[1], relist(temp))
But it seems like there has to be an easier way to do this (especially given the data.frame dimensions are identical).
Generically, what is the proper method of comparing 2 data frames element wise and writing the result to a 3rd data frame?
Upvotes: 0
Views: 90
Reputation: 59970
TRUE
and FALSE
are 1
and 0
repsectively so you should just be able to do this...
C <- ( A > B ) + 0
To exclude the first column just use [
to subset it like this:
C <- ( A[,-1] > B[,-1] ) + 0
And by way of example:
A <- data.frame( Date1 = as.POSIXct( Sys.Date()+101:105 ) , Date2 = as.POSIXct( Sys.Date()-1001:1005 ) )
# Date1 Date2
#1 2013-12-13 2010-12-07
#2 2013-12-14 2010-12-06
#3 2013-12-15 2010-12-05
#4 2013-12-16 2010-12-04
#5 2013-12-17 2010-12-03
B <- data.frame( Date1 = as.POSIXct( Sys.Date()+106:110 ) , Date2 = as.POSIXct( Sys.Date()-1006:1010 ) )
# Date1 Date2
#1 2013-12-18 2010-12-02
#2 2013-12-19 2010-12-01
#3 2013-12-20 2010-11-30
#4 2013-12-21 2010-11-29
#5 2013-12-22 2010-11-28
C <- ( A > B ) + 0
# Date1 Date2
#[1,] 0 1
#[2,] 0 1
#[3,] 0 1
#[4,] 0 1
#[5,] 0 1
Upvotes: 2