Dinoop Nair
Dinoop Nair

Reputation: 2773

compare two data frame and change one data frame in R

in R i have 2 dataFrames "df1" and "df2". They are as follows:

> df1
   date        value
1  1980-12-10       5
2  1980-12-11       5
3  1980-12-12       5
4  1980-12-13       5
5  1980-12-14       5


>df2
   date        value
1  1980-12-10       15
2  1980-12-11       2
3  1980-12-12       23
4  1980-12-13       44
5  1980-12-14       434
6  1980-12-15       242
7  1980-12-16       22
8  1980-12-17       82
9  1980-12-18       723
10 1980-12-19       72

I want to change "df2". The df2 must contains the values only if the df1 has the same date as df2. Actually i need the following output:

>df2
   date        value
1  1980-12-10       15
2  1980-12-11       2
3  1980-12-12       23
4  1980-12-13       44
5  1980-12-14       434

is it possible in R?

Upvotes: 0

Views: 117

Answers (3)

agstudy
agstudy

Reputation: 121568

You can use sqldf, to do an SQL INNER JOIN( R merge), for example:

library(sqldf)
sqldf('SELECT df2.*
       FROM df2
       INNER JOIN df1
       ON df1.date = df2.date')
        date value
1 1980-12-10    15
2 1980-12-11     2
3 1980-12-12    23
4 1980-12-13    44
5 1980-12-14   434

Upvotes: 1

James
James

Reputation: 66834

You can just use subsetting and %in%:

df2[df2$date%in%df1$date,]
        date value
1 1980-12-10    15
2 1980-12-11     2
3 1980-12-12    23
4 1980-12-13    44
5 1980-12-14   434

Upvotes: 2

Anthony Damico
Anthony Damico

Reputation: 6104

# read in both data frames
df1 <-
    read.table( h = TRUE , text = "date        value
    1980-12-10       5
    1980-12-11       5
    1980-12-12       5
    1980-12-13       5
    1980-12-14       5")

df2 <-
    read.table( h = TRUE , text = "date        value
    1980-12-10       15
    1980-12-11       2
    1980-12-12       23
    1980-12-13       44
    1980-12-14       434
    1980-12-15       242
    1980-12-16       22
    1980-12-17       82
    1980-12-18       723
    1980-12-19       72")

# merge df1 and df2, only keeping the date column from df1
# but note no comma, which maintains the `class` of df1,
# allowing the merge to work appropriately
merge( df1[ 'date' ] , df2 )

# and if you wanted to overwrite df2 with the new results:
df2 <- merge( df1[ 'date' ] , df2 )

Upvotes: 1

Related Questions