2017-01-03 69 views
-5

我有一個數據集,其中包括年份和月份組合形成一個整數。刪除R中整數的一部分

示例數據集:

dataset = c(201601, 201602, 201603, 201604,201605,201606,201607,201608,201609,201610, 201611 ,201612) 

我想在R. 每條記錄​​只提取月份部分的預期結果是:

dataset_months = c(01, 02, 03, 04,05,06,07,08,09,10,11,12) 

如何執行呢?

回答

3

你有望走出放似乎是一個字符串,我會建議你將留在整數世界效率和便利,像(這個想法的從here拍攝)

((dataset/100) %% 1) * 100 
## [1] 1 2 3 4 5 6 7 8 9 10 11 12 
## OR just `dataset - 201600` ? 

此使用substring(如果你願意,也很容易實現作爲回報character矢量)

substring(dataset, 5) 
# [1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12" 

或者你可以做一個日期操作

as.POSIXlt(paste0(as.character(dataset), "01"), format = "%Y%m%d")$mon + 1L 
# [1] 1 2 3 4 5 6 7 8 9 10 11 12 
3

我們可以通過操縱Date使用substr

substr(dataset, nchar(dataset)-1, nchar(dataset)) 
#[1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12" 

sub

sub(".{4}", "", dataset) 

或期權

library(zoo) 
format(as.yearmon(as.character(dataset), "%Y%m"), "%m") 
#[1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10" "11" "12"