Achal Neupane
Achal Neupane

Reputation: 5719

How to assign new data to the variable within variable in R

I have my file names as all.files in working directory. I want to read these files in loop and assign the names as gsub(".csv","", all.files) for each file.

all.files <- c("harvestA.csv", "harvestB.csv", "harvestC.csv", "harvestD.csv", 
"seedA.csv", "seedB.csv", "seedC.csv", "seedD.csv")

I tried something like this below but it won't work. What do I need here?

for(i in 1:length(all.files)){
  assign(gsub(".csv","", all.files)[i]) <- read.table(
    all.files[i],
    header = TRUE,
    sep = ","
  )
}

Upvotes: 1

Views: 71

Answers (3)

Dij
Dij

Reputation: 1378

An option using strsplit

for (i in seq_along(all.files)) {
      assign(x = strsplit(allfiles[i],"\\.")[[1]][1], 
             value = read.csv(all.files[i]),
             pos = .GlobalEnv)
    }

Upvotes: 0

akrun
akrun

Reputation: 886998

The . is a metacharacter in regex matching any character. So, we can use fixed = TRUE to match the literal dot. Also, in the OP's code, with the assign, there is no need for another assignment operator (<-), the second argument in assign is value and here it is the dataset read with the read.table

for(i in 1:length(all.files)){
     assign(sub(".csv","", all.files, fixed = TRUE)[i], read.table(
       all.files[i],
        header = TRUE,
        sep = ","
    ))
   }

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388862

You could keep them in a named list as it is not a good practice to clutter the environment with lot of global variables

list_df <- lapply(all.files, read.csv)
names(list_df) <- sub("\\.csv", "", all.files)

You can always extract individual dataframes as list_df[["harvestA"]], list_df[["harvestB"]] etc.

If you still need them as separate dataframes

list2env(list_df, .GlobalEnv)

Upvotes: 2

Related Questions