2013-12-13 14 views
1

有沒有辦法將R數據框中的日期作爲字符串存儲在使用RSQLite的SQLite中?目前,日期列存儲爲整數。在寫入SQLite之前,我可能會將所有日期轉換爲字符串,但由於我需要從函數寫入SQLite,因此數據框架是參數之一,我寧願避免這種轉換。RSQLite - 將日期列存儲爲SQLite中的字符

library('RSQLite') 

df <- data.frame(
     x=1:3, 
     y=as.Date(c('2011-01-01','2011-03-03','2011-12-31')) 
    ) 

df 

# Create connection and temporary database 
sqlite <- dbDriver("SQLite") 
tmpdb <- dbConnect(sqlite,"__this_is_temporary_db__.db")   

# Write data  
dbWriteTable(tmpdb,'df',df) 

# We get integers from date 
dbGetQuery(tmpdb,'select * from df') 

dbDisconnect(tmpdb)  

# file.remove('__this_is_temporary_db__.db') 
+1

見https://github.com/rstats-db/RSQLite/issues/17 – hadley

回答

3

你應該強制性格。您可以使用這樣的事情對所有data.frame日期列做到這一點:

ll <- lapply(df,function(x) 
    if(inherits (x,c('POSIXct','Date')) 
     as.character(x) 
    else x)) 
do.call(rbind.data.frame,ll) 
+0

...的主要原因是源碼沒有原生[日期類型](http://www.sqlite.org/datatype3.html)。 R將內部日期存儲爲整數。所以如果你想要角色,你必須以這種方式將它發送到sqlite。 – joran

+2

當您強制使用文本字段時,例如'dbSendQuery(tmpdb,「CREATE TABLE df(x INTEGER,y TEXT)」); dbSendPreparedQuery(tmpdb,「INSERT into df values(?,?)」,bind.data = df)'將其轉換爲真實外觀的文本。 –

+0

@TomasGreif修復。 – agstudy

相關問題