cbind() is changing date formatting

前端 未结 2 454
失恋的感觉
失恋的感觉 2021-02-04 03:18

I\'m trying to create a subset of a data frame and when I do so, R switches the formatting of the date column. Any idea why or how to fix this?

> head(spyPr2         


        
2条回答
  •  名媛妹妹
    2021-02-04 03:51

    I think I might call this a hidden instance of the drop = FALSE gotcha with data frames.

    When you use cbind, it only uses the data frame method if at least one of the components are also data frames. Otherwise, everything is converted to a single type in order to construct a matrix.

    Thus, calling cbind on elements like spyPr2$Date or spyPr2[,'Date'] will result in a matrix (losing the date structure), which will not be magically restored by wrapping it all in data.frame.

    You can do this if you use [ to select each column, but only by using drop = FALSE which prevents R from converting the result to a vector (which lands you right back where you started with R coercing the result to a matrix):

    cbind(spyPr2[,'Date',drop = FALSE],spyPr2[,'Close'])
    

    is sufficient, since you only need one of the components to be a data frame.

    But Gavin is right in general, you shouldn't be subsetting your data frame this way.

提交回复
热议问题