R にロードするのに十分小さいデータ フレームは、dbWriteTable
使用可能な RAM の最大量に近い場合、呼び出し中にメモリ制限の上限に達することがあります。以下のコードのようにテーブルをRAMにチャンクで読み込むよりも良い解決策があるかどうか疑問に思っていますか?
古いコンピューターで動作するコードを書こうとしているので、Windows 32 ビット バージョンの R を使用して、これらのメモリ エラーを再現しています。
# this example will only work on a computer with at least 3GB of RAM
# because it intentionally maxes out the 32-bit limit
# create a data frame that's barely fits inside 32-bit R's memory capacity
x <- mtcars[ rep( seq( nrow( mtcars ) ) , 400000 ) , ]
# check how many records this table contains..
nrow( x )
# create a connection to a SQLite database
# not stored in memory
library( RSQLite )
tf <- tempfile()
db <- dbConnect( SQLite() , tf )
# storing `x` in the database with dbWriteTable breaks.
# this line causes a memory error
# dbWriteTable( db , 'x' , x )
# but storing it in chunks works!
chunks <- 100
starts.stops <- floor( seq( 1 , nrow( x ) , length.out = chunks ) )
for ( i in 2:( length( starts.stops ) ) ){
if ( i == 2 ){
rows.to.add <- ( starts.stops[ i - 1 ] ):( starts.stops[ i ] )
} else {
rows.to.add <- ( starts.stops[ i - 1 ] + 1 ):( starts.stops[ i ] )
}
# storing `x` in the database with dbWriteTable in chunks works.
dbWriteTable( db , 'x' , x[ rows.to.add , ] , append = TRUE )
}
# and it's the correct number of lines.
dbGetQuery( db , "select count(*) from x" )