Search code examples
rxts

Update column value in XTS object based on date


             SCA-B.ST.Open  SCA-B.ST.High  SCA-B.ST.Low  SCA-B.ST.Close  BOUGHT
 2008-01-14      104.50      105.00         101.50         102.75
 2008-01-15      102.50      102.50         98.25          99.50

I have made an XTS object containing some stock info in R. I have also made a manual list (on paper) of when I entered a position with the stock containing values "B" or "S".

How do I go about to insert "B" or "S" values into the "BOUGHT" column based on the date index the XTS object provides?


Solution

  • You can simply do (here I assume your xts is called data):

    # add col with 'NA' values
    data$BOUGHT <- NA
    data[as.Date("2008-01-15"),"BOUGHT"] <- "B"
    # check/print
    data[as.Date("2008-01-15"),"BOUGHT"]
    

    output:

    > # add col with 'NA' values
    > data$BOUGHT <- NA
    > data[as.Date("2008-01-15"),"BOUGHT"] <- "B"
    > # check/print
    > data[as.Date("2008-01-15"),"BOUGHT"]
               BOUGHT
    2008-01-15 "B"