지방이의 Data Science Lab

[R] 날짜 열로 할 수 있는 컬럼관리 방법 본문

Data Analysis/깨R지식

[R] 날짜 열로 할 수 있는 컬럼관리 방법

[지현] 2019. 12. 28. 16:09

 

(데이터 크기가 커질수록 lubridate함수로 관리하는 것보다 string으로 들고 있는 것이 억만배 가볍다. 월별 추출도 string단위로 긁어오는게 훨씬 빠른 속도를 보인다.)


[2019.12.25 => 20191225]

library(stringr)

monthly$관리년월 = str_replace_all(monthly$관리년월, "[.]", "")

monthly$yearmonth = str_sub(monthly$yearmonth,1,7)

 


[201912 => 2019-12-01]

 

'몇일' 변수를 꼭 추가해야 하는 경우가 있다. (시각화)

예를들어 x축에 날짜를 넣고 싶은 경우가 그렇다. 

그럴때 보통 사용하는 코드가 이것:

temp$yearmonth = as.Date(ymd(paste0(temp$yearmonth,'01')))

 


[20191225=>2019-12-25]

library(stringi)

stri_sub(CUSTINFO$SALDT,5,4)="-";stri_sub(CUSTINFO$SALDT,8,7)="-" #20190324 => 2019-03-24

 

 

 


[요일]

방법1:

CUSTINFO$SALDT=as.Date(CUSTINFO$SALDT)

CUSTINFO$wday=strftime(CUSTINFO$SALDT,"%A")

 

방법2:

library(lubridate)

CUSTINFO$SALDT=ymd(CUSTINFO$SALDT)

CUSTINFO$wdays=wday(CUSTINFO$SALDT,label=TRUE)


[계절]

library(stringr)

temp1$month = str_sub(temp1$yearmonth,5,6)  
temp1$month = as.numeric(temp1$month) 
seasons = function(x){ 
  if(x %in% 2:4) return('Spring') 
  if(x %in% 5:7) return('Summer') 
  if(x %in% 8:10) return('Fall') 
  if(x %in% c(11,12,1)) return('Winter') 
} 
temp1$season = sapply(temp1$month, seasons)

Comments