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

Asked

Viewed 59 times

2

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

s <- Filename[i,1]
c <-  read.table(s)

1 answer

1

Assuming that all files have the same variable structure and can be merged with each other, 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 two 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.