Herr Student Herr Student - 3 months ago 13
R Question

Import-loop in R (read.csv)

I tried to import *.csv files with ongoing numbers in the mid of the name - so I tried to use a for-loop to generate the number and paste it into the filenames:

for (Number in 20:30){
(paste("Test.",Number,"File"))<- read.csv("~/Test.-",Number,"File".csv", sep=";", comment.char="#")

}


How can I avoid the blank, so the Import does work? Any other Suggestions?
Thanks a lot!

Answer

Anwer by @manaR solves the problem of the white space. The stringrpackage str_c allows you to do that also. You can use assign to create a new variable with the right name in the user environment.

require(stringr)
for (Number in 20:30){
        file<- read.csv(str_c("~/Test.-",Number,"File",".csv"), sep=";",comment.char="#")
        # assign value to the variable name x 
        assign(x=str_c("Test.",Number,"File"),value=file,envir=.GlobalEnv)  
      }



   # this example with the winprogressbar only works under windows
    # it allows you to load all the files with extension .csv in one directory


    datawd<-"c:/path/to/mydirectory/"
    listoffiles<-list.files(datawd) # list of files
    # find out which files have extensions csv
    listoffiles<-listoffiles[grep(".csv",listoffiles)]
    # creating the full path
    mypaths<-str_c(datawd,listoffiles)
    progress<-utils::winProgressBar(title = "loading csv files",
            label = "progression %",
            min = 0,
            max = length(mypaths), 
            initial = 0,
            width = 400)
    for (i in 1:length(mypaths)){
        utils::setWinProgressBar(progress,i,label=listoffiles[i])       
        file<- read.csv(mypaths, sep=";",comment.char="#")
        # assign value to the variable name x 
        assign(x=str_c("Test.",Number,"File"),value=file,envir=.GlobalEnv)  
    }