2015-06-21 26 views
3

我似乎無法將我的數據從csv轉換爲適當的日期類。我正在使用csv的1033日期。我已保存的格式爲「年月日」strptime錯誤R:輸入字符串太長

這裏是我的導入CSV(這似乎工作)代碼的CSV:

bd <- read.csv('birthdaysExample.csv', 
      header = FALSE, 
      sep = ',') 

我可以看到R中Studio中的數據:

> head(bd) 
     V1 
1 20141125 
2 20140608 
3 20140912 
4 20140526 
5 20140220 
6 20140619 

但是,當我嘗試轉換日期時收到錯誤: 「strptime中的錯誤(bd,format =」%Y%m%d「):輸入字符串太長。

下面是我的代碼:

better_bds <- strptime(bd,format='%Y%m%d') 

我甚至試圖檢查並確認所有的日期其實是有8個字:

> table(nchar(bd$V1) != 8 | nchar(bd$V1) != 8) 

FALSE 
1033 

所以我不知道如果有人能夠指引我走向正確的方向,那麼下一步該轉向哪裏,我將不勝感激!

+4

'better_bds < - data.frame(bd = strptime(bd [,1],format ='%Y%m%d'))'' – Hugh

回答

3

問題是bd是一列data.frame和strptime期望一個字符向量。如果您未將字符向量傳遞到strptime,則會通過as.character(x)傳遞給您。調用as.character(bd)會導致您可能不期望的結果。

bd <- structure(list(V1 = c(20141125L, 20140608L, 20140912L, 20140526L, 
    20140220L, 20140619L)), .Names = "V1", class = "data.frame", 
    row.names = c(NA, -6L)) 
as.character(bd) 
# [1] "c(20141125, 20140608, 20140912, 20140526, 20140220, 20140619)" 

你需要把它傳遞給strptime(如Hugh suggested in his comment)之前,子集bd的特徵向量列。

strptime(bd[,1], format="%Y%m%d") 

此外,由於您似乎沒有任何實際的時間信息,我建議您改用Date類。這將防止您遇到任何潛在的時區問題。

as.Date(as.character(bd[,1]), format="%Y%m%d") 
0

您可以用

better_bds <- sapply(bd,function(x) strptime(x,format='%Y%m%d')) 

隨着輸入數據試試,我獲得

> better_bds 
$V1 
[1] "2014-11-25 CET" "2014-06-08 CEST" "2014-09-12 CEST" "2014-05-26 CEST" "2014-02-20 CET" "2014-06-19 CEST" 
0

實際的日期格式必須與strptime函數內部日期格式的同步。例如如下:

> x <- c("2006-01-08", "2006-08-07") 
> strptime(x, "%Y-%m-%d") 
[1] "2006-01-08" "2006-08-07" 

> y <- c("2006/01/08", "2006/08/07") 
> strptime(y, "%Y/%m/%d") 
[1] "2006-01-08" "2006-08-07" 

,如果你嘗試不同的,它會顯示錯誤:

> x <- c("2006-01-08", "2006-08-07") 
> strptime(x, "%Y/%m/%d") 
[1] NA NA 

> y <- c("2006/01/08", "2006/08/07") 
> strptime(y, "%Y-%m-%d") 
[1] NA NA 

> x <- c("20060108", "20060807") 
> strptime(x, "%Y-%m-%d") 
[1] NA NA 
> x <- c("20060108", "20060807") 
> strptime(x, "%Y-%m-%d") 
[1] NA NA 

希望這有助於。