How do I use lapply to upload files to the global environment?

I have the following working code:

############################################
###Read in all the wac gzip files###########
###Add some calculated fields ###########
############################################
library(readr)
setwd("N:/Dropbox/_BonesFirst/65_GIS_Raw/LODES/")
directory<-("N:/Dropbox/_BonesFirst/65_GIS_Raw/LODES/")
to.readin <- as.list(list.files(pattern="2002.csv"))

LEHD2002<-lapply(to.readin, function(x) {
  read.table(gzfile(x), header = TRUE, sep = ",", colClasses = "numeric", stringsAsFactors = FALSE)
})

      

But I would like to load things from lapply into the global environment, for debugging.

This provides a way to do this.

# Load data sets
  lapply(filenames, load, .GlobalEnv)

      

But when I try to use it I get the following error:

Error in FUN (X [[i]], ...): Invalid number of recovery files (file may be damaged) - no data loaded Also: Warning message: file 'Az_wac_S000_JT00_2004.csv.gz has magic number' w_geo ' Using preservation version 2 is deprecated

Am I doing something wrong, or is the "load" out of date or the like?

gzfile (x) converts the .gz (zipped) file to .csv, so it shouldn't be a problem ...

0


source to share


1 answer


load

downloads files in binary format (such as .rda

files). You download files in text format .csv

. This is why you are using read.table

. When you try to read text formatted files with load

, you will get this error.

Usage:, lapply(filenames, load, .GlobalEnv)

goes from .GlobalEnv

to load

, not to lapply

. It's just a different way of reading a list of files that are in a different format than yours. load

can put objects in a different environment as a way to protect you from overwriting objects in the current environment with the same name as the objects you load. Binaries created with save

(which you can load with load

) carry their names with them. When you download them, you do not assign a name to them. They are available in the environment where you choose to download them with their original name.



Both methods load objects into .GlobalEnv

. This way your code works the way you want. You can tell that your objects were somehow not read in another environment by trying to access them after running the code. If you can access them using the object you named with

+1


source







All Articles