Essi
Essi

Reputation: 801

Extract part of file name and add it into a dataframe list

I have a list of dataframes that looks like this:

enter image description here

I have filenames like this:

testlist
"Folder1/AT0ILL10000700500dymax.1-1-1990.31-12-2011"       
"Folder1/CH0001A0000700100dymax.1-1-1992.31-12-2007"
"Folder1/CH0005A0000700500dymax.1-1-1992.31-12-2011" 

I read the data with this command.

data_list = lapply(testlist, read.table)

Now I want to extract a part of the filename and add it into the dataframe as V6. These are the parts I want to extract.

AT0ILL1
CH0001A
CH0005A

So this would be the 9-15 letters, and in the first dataframe [1] would only contain 6 times"AT0ILL1" in the last new column, [[2]] would only be "CH0001A" in V6 and in [[3]] only "CH0005A".

I can do it for example with only one file with:

substr(name, 9, 15)

But how can I do it with all files (in reality I have over 1000)?

Here is the code of my testframe from the beginning.

V1= c("20000608", "20000609", "20000610", "20000611", "20000612", "20000613")
V2= seq(5, 30, length=6)
V3= rep(c(-1,0,1), times=2) 
V4= seq(10, 60, length=6) 
V5= rep(c(1,-1,0), times=2) 

testframe1 = data.frame(V1, V2, V3, V4, V5) 

x1= c("20030608", "20100609", "20060610", "20040611", "20009612", "20002613")
x2= seq(4, 80, length=6)
x3= rep(c(0,-1,1), times=2) 
x4= seq(3, 60, length=6) 
x5= rep(c(-1,1,0), times=2) 

testframe2 = data.frame(V1=x1, V2=x2, V3=x3, V4=x4, V5=x5) 

a1= c("20030602", "20100606", "20060610", "20040511", "20007612", "20002624")
a2= seq(7, 133, length=6)
a3= rep(c(-1,0,1), times=2) 
a4= seq(9, 47, length=6) 
a5= rep(c(1,0,-1), times=2) 

testframe3 = data.frame(V1=a1, V2=a2, V3=a3, V4=a4, V5=a5) 

list = list(testframe1, testframe2, testframe3)

Upvotes: 1

Views: 2240

Answers (1)

storaged
storaged

Reputation: 1847

What about simple for solution?

#  I assume that: 
# - testlist is a vector that contains filenames
# - df.list is a list of dataframes (in the example named list)
for(i in 1:3){
   df.list[[i]]$V6 <- substr(testlist[i], 9, 15)
}

Upvotes: 1

Related Questions