Masi Masi - 1 month ago 7
R Question

How to make loopable string list in R?

I am trying to make a minimum example for the data set of my other question.
Currently, I have the following which is too complicated and errorprone for having a list of filenames and appending them for full filenames

data = read.csv("/home/masi/dataList.csv",header = FALSE,sep = ",")
i = 1
for (d in data) {
data[i] = paste("/home/masi/Documents/CSV/", d, sep="")
i = i + 1
}


dataList.csv

P103C1.csv
P103C2.csv
P111C1.csv


Pseudocode to have in columns the thing first and transpose but you still cannot loop it as
for (d in data) {...}
; and appending once again

data = t(c("P103C1.csv" "P103C2.csv" "P111C1.csv"))

i = 1
for (d in data) {
data[i] = paste("/home/masi/Documents/CSV/", d, sep="")
i = i + 1
}


Actually, I think having the transpose there is not a good idea and a better and simpler method should exist.

Expected output: something equivalent to
data = read.csv("/home/masi/dataList.csv",header = FALSE,sep = ",")
.

OS: Debian 8.5

R: 3.1.1

Answer

You dont need to create a string in this case as you already have all the files in datalist.csv. Create a list out of datalist.csv and then feed into a loop.

listoffiles=list("P103C1.csv","P103C2.csv","P111C1.csv")
files=list()

for(i in 1:length(listoffiles)){
    files[[i]]=read.csv(listoffiles[[i]], header = F, sep = ',')
    }