Question

I've tried to integrate a xts datum into my data frame, but I don't know how to do it, below is an example of the error I encounter.

library(xts)
data(sample_matrix)
xtsObject=as.xts(sample_matrix) 
#load xts and build in data sample_matrix


data=data.frame(Open=numeric(),
                High=numeric(),
                Low=numeric(),
                Close=numeric())
#create an empty data frame

data[,"Open"]=xtsObject[,"Open"]
#put data in(encounter error)

error code: Error in [<-.data.frame(*tmp*, , "Open", value = c(50.0397819115463, : replacement has 180 rows, data has 0

To jihoward: ya you are right, but I want to set the column names when I build the data frame. I didn't get the column name I want, for example

xtsObject=as.xts(sample_matrix) 
data <- data.frame("colnames"=xtsObject$Open)
head(data) 
#               Open
#2007-01-02 50.03978
#2007-01-03 50.23050
       ...

In this example the column name which I want is "colnames", but it changes to "Open". So I choose the "Another way", first build the data frame I want, then put the data in, or perhaps you have a better solution?

Was it helpful?

Solution

Unless I'm missing something, you're doing much more work than necessary.

# convert to data.frame
data <- data.frame(xtsObject)
head(data)
#                Open     High      Low    Close
# 2007-01-02 50.03978 50.11778 49.95041 50.11778
# 2007-01-03 50.23050 50.42188 50.23050 50.39767
# 2007-01-04 50.42096 50.42096 50.26414 50.33236
# 2007-01-05 50.37347 50.37347 50.22103 50.33459
# 2007-01-06 50.24433 50.24433 50.11121 50.18112
# 2007-01-07 50.13211 50.21561 49.99185 49.99185

# only one column
data <- data.frame(xtsObject$Open)
head(data)
#                Open
# 2007-01-02 50.03978
# 2007-01-03 50.23050
# 2007-01-04 50.42096
# 2007-01-05 50.37347
# 2007-01-06 50.24433
# 2007-01-07 50.13211


# Another way
data <- data.frame(Open=numeric(), High=numeric(), Low=numeric(), Close=numeric())
data[1:nrow(xtsObject[,"Open"]) ,"Open"] <- xtsObject[,"Open"]
head(data)
#       Open High Low Close
# 1 50.03978   NA  NA    NA
# 2 50.23050   NA  NA    NA
# 3 50.42096   NA  NA    NA
# 4 50.37347   NA  NA    NA
# 5 50.24433   NA  NA    NA
# 6 50.13211   NA  NA    NA

Notice the difference in row names with the last option.

EDIT (Response to OP's addendum)

You could just set the column names after; this is probably the most straightforward.

data <- data.frame(xtsObject$Open)
colnames(data) <- "colname"

or, you could do it this way:

data <- data.frame(colname=as.data.frame(xtsObject)$Open)

If the column name, Open, is actually stored in a variable, then you could use:

openCol <- "Open"
data <- data.frame(colname=as.data.frame(xtsObject)[[openCol]])

Note the use of [[openCol]], and not [openCol].

OTHER TIPS

data has no rows, so you have to specify them:

data[1:nrow(xtsObject[,"Open"]) ,"Open"] <- xtsObject[,"Open"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top