[R] Adding two files into one and vlookup

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jul 7 02:30:15 CEST 2010


On Tue, Jul 6, 2010 at 8:26 PM, Gabor Grothendieck
<ggrothendieck at gmail.com> wrote:
> On Tue, Jul 6, 2010 at 6:18 PM, raghu <r.raghuraman at gmail.com> wrote:
>>
>> I have two files with dates and prices in each. The number of rows in each of
>> them will differ. How do I create a new file which contains data from both
>> these files? Cbind and merge are not helpful. For cbind because the rows are
>> not the same replication occurs. Also if I have similar data how do I write
>> a vlookup kind of function? I am giving an example below:
>> Say Price1 file contains the following:
>> Date             Price
>> 2/3/2010       134.00
>> 3/3/2010       133.90
>> 4/3/2010       135.55
>>
>> And say price2 contains the following:
>> Date              Price
>> 2/3/2010        2300
>> 3/3/2010        3200
>> 4/3/2010        1800
>> 5/3/2010        1900
>>
>> I want to take both these data together in a single file, and take the
>> smaller vector (or matrix or dataframe??..i am new to R and still confused
>> with the various objects) which is file1 (because it contains fewer rows )
>> and vlookup prices in the second file basedon the dates on file1 and write
>> three columns (date, price from 1 and price from2) in a new file. How do i
>> do this please?
>>
>
> Try this and for more read the three vignettes (pdf documents) in the
> zoo package and also read the R News 4/1 article on dates and times:
>
> Lines1 <- "Date             Price
> 2/3/2010       134.00
> 3/3/2010       133.90
> 4/3/2010       135.55"
>
> Lines2 <- "Date              Price
> 2/3/2010        2300
> 3/3/2010        3200
> 4/3/2010        1800
> 5/3/2010        1900"
>
> library(zoo)
> library(chron)
> z1 <- read.zoo(textConnection(Lines1), header = TRUE, FUN = chron)
> z2 <- read.zoo(textConnection(Lines2), header = TRUE, FUN = chron)

I originally assumed that the dates were the usual month/day/year but
looking at it again I suspect they are day/month/year so lets use Date
class instead of chron replacing the last three statements with:

fmt <- "%d/%m/%Y"
z1 <- read.zoo(textConnection(Lines1), header = TRUE, format = fmt)
z2 <- read.zoo(textConnection(Lines2), header = TRUE, format = fmt)





> merge(z1, z2) # keep all rows in each
> merge(z1, z2, all = FALSE) # keep only rows in both
> merge(z1, z2, all = c(TRUE, FALSE)) # keep all rows in z1
> merge(z1, z2, all = c(FALSE, TRUE)) # keep all rows in z2
>



More information about the R-help mailing list