How to read a file if its name is stored in a variable?

2

I have a file with names of other 980 files actually, so I wanted to read that file and save the names in a variable and then open the file with that name, I tried with the read table but as the name is in a variable it does not recognize. Any solution for this?

s <- Filename[i,1]
c <-  read.table(s)
    
asked by anonymous 17.04.2017 / 09:49

1 answer

1

Assuming all files have the same variable structure and can be merged together, the code below should work. If the imported files are xls, or another format, they can be parameterized by the import function itself. In this example, each file had only 1 line and 2 variables.

# adiciona o nome dos arquivos do diretório no vetor "arquivos"
arquivos <- dir()

print(arquivos) 
# "1.txt" "2.txt" "3.txt"

# cria um data.frame que será a base 
base <- data.frame(read.table(arquivos[1]))

head(base)
#   V1 V2
# 1 10 11

# faz o laço de todos os arquivos seguintes
for(i in 2:length(arquivos)){
  base2 <- data.frame(read.table(arquivos[i]))
  base <- rbind(base, base2)
}

head(base)
#   V1 V2
# 1 10 11
# 2 20 21
# 3 30 31
    
19.04.2017 / 07:46