繁体   English   中英

使用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

我们可以使用cSplitsplitstacshape将定界符-分隔“日期”列。

 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 我们指定sepcbind名称,并与原始列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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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