2017-06-13 37 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