Using bigmemory package in R to solve the Ram memory problem

30 views Asked by At

I need to convert some databases that, although they are large to manipulate (due to RAM), are stored locally on my computer. To simulate my work situation, I used the car sales database available at https://www.kaggle.com/datasets/syedanwarafridi/vehicle-sales-data and replicated it 92 times with the name pattern "car_prices1", ... "car_prices92". I'm trying to create code that reads the 92 bases in csv format and exports them in dbf format.

rm(list = ls())

# Carregue os pacotes necessários
install.packages("bigmemory")
install.packages("bigmemory.sri")

library(bigmemory)
library(bigmemory.sri)

# Defina o diretório onde estão localizados os arquivos
diretorio <- "C:/Users/bruna/OneDrive/Área de Trabalho"
arquivos <- list.files(diretorio, pattern = "car_prices")

# Verifique se há arquivos correspondentes
if (length(arquivos) > 0) {
  # Crie um big.matrix para armazenar os dados
  bm <- big.matrix(
    nrow = 1,  
    ncol = 1,  
    type = "integer",  
    backingfile = "temp_backingfile",  
    descriptorfile = "temp_descriptorfile"  
  )
  
  # Itere sobre cada arquivo e leia-os
  for (arquivo in arquivos) {
    caminho_do_arquivo <- file.path(diretorio, arquivo)
    
    # Leia o arquivo CSV
    dados <- read.csv(caminho_do_arquivo)
    
    # Converta os dados para um big.matrix
    bm_temp <- as.big.matrix(dados)
    
    # Combine os big.matrices
    bm <- rbind(bm, bm_temp)
    
    # Crie o nome do arquivo DBF
    nome_arquivo_dbf <- sub(".csv$", ".dbf", arquivo)
    
    # Caminho do arquivo DBF de saída
    caminho_arquivo_dbf <- file.path(diretorio_saida, nome_arquivo_dbf)
    
    # Salve os dados como arquivo DBF
    write.dbf(as.data.frame(dados), caminho_arquivo_dbf)
  }
  
  # Remova a primeira linha (cabeçalho inicial) que foi criada com nrow = 1
  bm <- bm[-1, ]
  
  # Faça o que precisar com os dados combinados
  # Por exemplo, para visualizar as primeiras linhas do big.matrix
  print(head(bm))
  
  # Salve o big.matrix como um arquivo RData
  save(bm, file = file.path(diretorio_saida, "big_matrix.RData"))
  
} else {
  print("Nenhum arquivo encontrado com 'car_prices' no nome.")
}

After running the code, I have the following error: Error in write.dbf(as.data.frame(dados), dbf_file_path) : unable to open file

0

There are 0 answers