hash
hash

Reputation: 103

assign each read file to different variables

I am trying to read 100 files into R by assigning different variable name to each file but I get the following error message

Error in sprintf("read_data_%d", 1) <- readRDS(sprintf("/home/data/Desktop/read_data_%s.rds", : target of assignment expands to non-language object

Here is my code

for (i in 1:100) 
{
     sprintf("read_data_%d", [i]) <- readRDS(sprintf("/home/data/Desktop/read_data_%s.rds", filenames[i]))
}

Thanks

Upvotes: 0

Views: 358

Answers (3)

B A
B A

Reputation: 1

In tidy style, if you want to read a series of files into separate objects you can set up a data frame with two columns: the new object name, and its file path. Then use pmap to step through each row and assign each file to a separate object:

name_file_tbl %>% select(obj_name,fpath) %>% 
pmap( function(obj_name, fpath){
assign(obj_name, readRDS(fpath), envir = .GlobalEnv )
})

Upvotes: 0

Toby Penk
Toby Penk

Reputation: 126

I echo DGKarlsson's sentiment that it may be easier to store this data in a list; however, if you did want to make separate objects for each file's output (for example, if each file is a data frame with a different set of columns), you can use the assign() function:

assign(variable_name,variable_value)

The problem with the original solution was that it attempted to assign a value to the output of sprintf(); however, the output of sprintf() is a string and can't be assigned a value.

Upvotes: 1

DGKarlsson
DGKarlsson

Reputation: 1101

For most applications it would be easier to store all of the data in a list:

read_data <- list()
for (i in 1:100)
    read_data[i] <- readRDS(sprintf("read_data_%s.rds", filenames[i]))

Then you can access the data from file number i using

read_data[[i]]

Upvotes: 1

Related Questions