Stataq
Stataq

Reputation: 2297

how to rewrite a looping code with lapply

I have a code

for (i in 1:length(datasets)) assign(datasets[i], read.csv(paste0(file_dir,datasets[i]),stringsAsFactors = FALSE, header = TRUE))

I want to rewrite it with lapply. How should I do it?

Upvotes: 1

Views: 42

Answers (2)

akrun
akrun

Reputation: 887118

We can use tidyverse methods

library(dplyr)
library(readr)
library(readr)
datasetList <- map(datasets, ~ read_csv(file.path(file_dir, .x)))
names(datasetList) <- datasets

Upvotes: 1

Jonas
Jonas

Reputation: 1810

The code

datasetList <- lapply(datasets, function(datasetname) {
  read.csv(paste0(file_dir,datasetname),stringsAsFactors = FALSE, header = TRUE)
}

will give you a list of datasets. You can access the i-th dataset by calling datasetList[[i]]

If you want to access the datasets by their names, just name the list via

datasetList <- setNames(datasetList,datasets)

and you can access a dataset called "datasetXXX" via datasetList$datasetXXX or datasetList[[datasetXXX]]

Upvotes: 2

Related Questions