2017-06-13 66 views
0

我想将一列拆分为三列,因此我可以给出日期格式。 目前数据集看起来像这样按给定数量的字符拆分数字列数据

YYYYMMDD   Number 
20020101   0.21 
20020102   0.34 
20020103   1.22 

我希望它看起来像这样

Year Month Day Number 
2002 01  01 0.21 
2002 01  02 0.34 
2002 01  03 1.22 

我有下面的代码编写的,它在,我可以拆分列感的作品,但这样做我创建新的数据帧,而且我不确定如何再在data.frame添加回原在data.set

  • 集=数据

有没有更好的方法来做到这一点?或如何获得new2 + new与数据结合?

res <- strsplit(data$YYYYMMDD, "(?<=.{4})" , perl = TRUE) 
new<-do.call(rbind, res) 
summary(new) 
colnames(new)<-c("Year", "MMDD") 
new<-as.data.frame(new) 
new$MMDD<-as.character(new$MMDD) 
res <- strsplit(new$MMDD, "(?<=.{2})" , perl = TRUE) 
new2<-do.call(rbind, res) 
summary(new2) 
colnames(new2)<-c("Month", "Dom") 
new2<-as.data.frame(new2) 
+1

怎么样一个简单的'$ DF年< - SUBSTR(as.character(DF $年月日),1,4)'等等? –

回答

1

我们可以很容易地与separate

library(tidyr) 
separate(df1, YYYYMMDD, into = c('Year', 'Month', 'Day'), sep=c(4, 6)) 
# Year Month Day Number 
#1 2002 01 01 0.21 
#2 2002 01 02 0.34 
#3 2002 01 03 1.22 
+1

谢谢,那有效。我不知道我为什么要以这种复杂的方式去讨论它 – Fosulli

2

做到这一点随着substring

x <- mapply(substring, c(1, 5, 7), c(4, 6, 8), 
      MoreArgs = list(text = df$YYYYMMDD), SIMPLIFY = F) 
names(x) <- c('Year', 'Month', 'Day') 
cbind(as.data.frame(x), df[-1]) 
# Year Month Day Number 
# 1 2002 01 01 0.21 
# 2 2002 01 02 0.34 
# 3 2002 01 03 1.22 
1

你可以试试这个(与你的变量年月日为字符):

year = substr(data$YYYYMMDD,1,4) 
month = substr(data$YYYYMMDD,5,6) 
day = substr(data$YYYYMMDD,7,8) 

new_data = as.data.frame(cbind(year,month,day,data$Number)) 
colnames(new_data)[4] = "Number" 
0

你可以用lubridate做到像这样:


library(tidyverse) 
library(lubridate) 

data %>% 
    mutate(
    YYYYMMDD = as.Date(as.character(YYYYMMDD), format = "%Y%m%d"), 
    year = year(YYYYMMDD), 
    month = month(YYYYMMDD), 
    day = mday(YYYYMMDD) 
    ) 
#>  YYYYMMDD Number year month day 
#> 1 2002-01-01 0.21 2002  1 1 
#> 2 2002-01-02 0.34 2002  1 2 
#> 3 2002-01-03 1.22 2002  1 3 
+0

我不认为它会被加载'library(tidyverse)' – yeedle