Home > front end >  problem with loops: creating names based on increasing values for reading in CSV file
problem with loops: creating names based on increasing values for reading in CSV file

Time:10-23

Okay, so I needed to split a larger file into a bunch of CSV's to run through a non-R program. I used this loop to do it:

for(k in 1:14){
  inner_edge = 2000000L*(k-1)   1
  outter_edge = 2000000L*(k)
  part <- slice(nc_tu_CLEAN, inner_edge:outter_edge)
  out_name = paste0("geo/geo_CLEAN",(k),".csv")
  write_csv(part,out_name)
  Sys.time()
}

which worked great. Except I'm having a problem in this other program, and need to read a bunch of these back in to trouble shoot. I tried to write this loop for it, and get the following error:

for(k in 1:6){
  csv_name <- paste0("geo_CLEAN",(k),".csv")
  geo_CLEAN_(k) <- fread(file= csv_name)
}

|--------------------------------------------------|
|==================================================|
Error in geo_CLEAN_(k) <- fread(file = csv_name) : 
  could not find function "geo_CLEAN_<-"

I know I could do this line by line, but I'd like to have that be a loop if possible. What I want is for geo_CLEAN_1 to relate to fread geoCLEAN1.csv; geo_CLEAN_2 to relate to fread geoCLEAN2.csv, etc.

CodePudding user response:

We need assign if we are interested in creating objects

for(k in 1:6){
  csv_name <- paste0("geo_CLEAN",(k),".csv")
  assign(sub("\\.csv", "", csv_name), fread(file= csv_name))
}
  •  Tags:  
  • r
  • Related