简体   繁体   中英

Square brackets and dataframes in R

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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM