2016-06-30 13 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]は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 

の代わりに、4月に発生しているが、私はあなたのコードを実行すると、私は正しいヶ月を取得、

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から月と日を抽出するには、次の2つの方法があります。

最初にデータを読むときに、文字列が要因に変換されないようにする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

私は使用せず、月名を抽出しようとしていました日付関数。はい、それはより複雑になります。 –

関連する問題