0

I am all too inexperienced in programming generally and R specifically so please forgive me if what I have is bad coding.

The problem I am trying to solve is to load many separate csv files into R, tidy up the input a bit, perform a few operations on the resulting objects and eventually plot the results of those operations. The way I have tried to solve it is to use a vector of strings which echoes the object names to call the objects in question. This does not work.

Below is a bit of code which after loading the data does not work.

files=list.files('foldername',pattern="*.csv",full.names=F) #Make a list of files
filen=str_extract(files, '.*(?=\\.csv)') #Pretty the file names for object names

for (i in 1:length(files)){
   assign(paste(filen[i]),read.csv(paste(files[i]))) #Load the files
   as.object(filen[i])=as.object(filen[i])[,order(names(ATCN_21))] # pseudocode line
   as.object(filen[i])=operation(as.object(filen[i]),parameter 1, parameter 2, etc) #More pseudocode
}

where operation may be a plot command or an arbitrary function such as rbind, colnames, whatever you may fancy.

In other words: I need some way to use string i in vector filen exactly as if it were an object name. How can I do this?

3
  • 4
    Instead of creating separate variables, have you tried lists? i.e. lst[[i]] <- filen[i]
    – Pierre L
    Oct 8, 2015 at 12:32
  • set ?get which is referenced in ?assign IIRC
    – Tensibai
    Oct 8, 2015 at 12:32
  • 1
    Just as a side note, since the "pattern" argument uses regular expression, it is better to use the pattern="\\.csv$" . R will understand the unescaped dot as any character. The final "$" specifies that the csv should be the end of the file name
    – user5363218
    Oct 8, 2015 at 12:34

1 Answer 1

0

The solution: Lists. (Thank you, Pierre)

files=list.files('foldername',pattern="\\.csv$",full.names=F) #Make a list of files
filen=str_extract(files, '.*(?=\\.csv)') #Pretty the file names for object names

list=lst()


for (i in 1:length(files)){
   lst[[i]]=read.csv(paste(files[i]))#Load the files
   names(lst)[i]<-filen[i] #Name the entries
   lst[[i]]=lst[[i]][,order(names(lst[[i]]))]

   lst[[i]]=operation(foo)
}

Thank you for helping a clueless n00b.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.