Reputation: 87
Okay I am rather puzzled by the different behaviours of dataframes and xtses in R and I'm hoping someone can explain it to me.
df = as.data.frame(x = c(1,2),row.names = c("2012-12-12","2012-12-13"))
xts = as.xts(x=c(1,2),order.by = as.POSIXct(c("2012-12-12","2012-12-13")))
I have two different datasets here. When you print them, they look almost similar. When I want the first row of the xts, xts[1,]
returns the row with colnames and the index. But when you do df[1,]
it only returns a vector.
Is there a way to return the first row of the dataframe, complete with the rownames and colname? I'm aware that I can hack it by doing as.data.frame(as.xts(df)[1,])
but is there a more elegant solution?
Upvotes: 1
Views: 1133
Reputation: 7630
This is a very particular case where a subsetting operation by rows on a data frame has only ONE cell.
In that case, you need to specify drop = FALSE
, here
df[1, , drop = FALSE]
I'd add a recommendation that when you create a data frame from scratch, use the data.frame()
function instead of as.data.frame()
Upvotes: 2