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]
.