2016-06-30 44 views
0

我有以下數據集。我試圖將date_1字段分成幾個月和幾天。然後將月份編號轉換爲月份名稱。month.abb []導致結果不正確

date_1,no_of_births_1 
1/1,1482 
2/2,1213 
3/23,1220 
4/4,1319 
5/11,1262 
6/18,1271 

我使用month.abb[]月號轉換成名稱。但不是爲月份號碼的每個值提供月份名稱,結果是生成錯誤的數組。 例如:month.abb[2]正在生成的,而不是二月

date_1 no_of_births_1 V1 V2 month 
1 1/1   1482 1 1 Jan 
2 2/2   1213 2 2 Apr 
3 3/23   1220 3 23 May 
4 4/4   1319 4 4 Jun 
5 5/11   1262 5 11 Jul 
6 6/18   1271 6 18 Aug 
下面

四月是我使用的代碼,

birthday<-read.csv("Birthday_s.csv",header = TRUE) 
birthday$date_1<-as.character(birthday$date_1) 
#split the data 
listx<-sapply(birthday$date_1,function(x) strsplit(x,"/")) 
library(base) 
#convert to data frame 
mat<-as.data.frame(matrix(unlist(listx),ncol = 2, byrow = TRUE)) 
#combine birthday and mat 
birthday2<-cbind(birthday,mat) 
#convert month number to month name 
birthday2$month<-sapply(birthday2$V1, function(x) month.abb[as.numeric(x)]) 

回答

0

當我運行代碼,我得到正確的月份。但是,你的代碼比必要的更復雜。以下是從date_1中提取月份和日期的兩種方法:

首先,當您讀取數據時,請使用stringsAsFactors=FALSE,這可以防止字符串轉換爲因子。

birthday <- read.csv("Birthday_s.csv",header = TRUE, stringsAsFactors=FALSE) 

提取月份和天使用日期函數:

library(lubridate) 

birthday$month = month(as.POSIXct(birthday$date_1, format="%m/%d"), abbr=TRUE, label=TRUE) 
birthday$day = day(as.POSIXct(birthday$date_1, format="%m/%d")) 

提取月份和天使用正則表達式:

birthday$month = month.abb[as.numeric(gsub("([0-9]{1,2}).*", "\\1", birthday$date_1))] 
birthday$day = as.numeric(gsub(".*/([0-9]{1,2}$)", "\\1", birthday$date_1)) 
+0

我試圖不使用提取月份名稱日期功能。是的,它變得更加複雜。 –