Barry
Barry

Reputation: 739

How to subset two files based on one column in common?

How to subset two files based on one column in common?

I have two text files that have one column with same structure, which is a date year-m-d.

   > head(wg)
        date  valu1   
 40034 2008-01-01 0.323   
 40058 2008-01-02 0.314 
  > head(reg)
    date      dval
 1 2008-01-01        0.225
 2 2008-01-02        0.235

To read one file:

 wg= read.table("C:\\Users\\wg.txt", sep ='' , header =TRUE)

But one of the two files has some dates missing so the number of rows is different between wg and regand I cannot do any calculation. Now what I need is to subset wg and reg where they are both available (based on date) ,as a result, both wg and reg have the same date and number of rows. I appreciate any help.

Upvotes: 1

Views: 169

Answers (1)

Ruthger Righart
Ruthger Righart

Reputation: 4921

Data example

A<-as.Date(c("2008-01-01", "2008-01-02", "2008-01-03"))
valA<-as.numeric(c(0.333, 0.232, 0.123))
B<-as.Date(c("2008-01-01", "2008-01-02", "2008-01-04"))
valB<-as.numeric(c(0.225, 0.124, 0.345))

wg<-data.frame(A, valA)
reg<-data.frame(B, valB)

v1<-wg$A %in% reg$B

The selected rows for wg:

wg[v1, ]

To get the row numbers for reg you need to run the %in% the other way around

Upvotes: 3

Related Questions