在 R 中使用 colsplit 重塑数据

Reshape data using colsplit in R

我尝试使用此代码重塑我的数据,但我得到了 NA 值。

require(reshape2)
dates=data.frame(dates=seq(as.Date("1988-01-01"),as.Date("2011-12-31"),by="day"))
first=dates[,1]
dates1=cbind(dates[,1],colsplit(first,pattern="\-",names=c("Year","Month","Day")))###split by y/m/day
 head(dates1)
   dates[, 1] Year Month Day
  1 1988-01-01 6574    NA  NA
  2 1988-01-02 6575    NA  NA
  3 1988-01-03 6576    NA  NA
  4 1988-01-04 6577    NA  NA
  5 1988-01-05 6578    NA  NA
  6 1988-01-06 6579    NA  NA

我们可以使用 splitstacshape 中的 cSplit 通过分隔符 - 拆分 'dates' 列。

 library(splitstackshape)
 cSplit(dates, 'dates', '-', drop=FALSE)

extract创建额外的列

library(tidyr)
extract(dates, dates, into=c('Year', 'Month', 'Day'),
                     '([^-]+)-([^-]+)-([^-]+)', remove=FALSE)

tidyr 中的另一个选项(@Ananda Mahto 建议)

separate(dates, dates, into = c("Year", "Month", "Day"), remove=FALSE)

或使用 base R 中的 read.table。我们指定 sep 和列名称,并使用原始列指定 cbind

cbind(dates[1],read.table(text=as.character(dates$dates),
                  sep='-', col.names=c('Year', 'Month', 'Day')))

通过使用 reshape2_1.4.1,我可以重现错误

  head(cbind(dates[,1],colsplit(first,pattern="-",
                   names=c("Year","Month","Day"))),2)
  #  dates[, 1] Year Month Day
  #1 1988-01-01 6574    NA  NA
  #2 1988-01-02 6575    NA  NA