3

I need to write multiple variables (dataframes) into different .txt files, named based it's original variables names. I tried use ls() function to select by pattern my desirable variables, but with no success. Is there any other approach to do this?

Using ls() function I was able to create .txt files with the correct filenames based on my variables (data1_tables.txt, data2_tables.txt, etc), but with the wrong output.

#create some variables based on mtcars data
data1 <- mtcars[1:5,]
data2 <- mtcars[6:10,]
data3 <- mtcars[11:20,]



fileNames=ls(pattern="data",all.names=TRUE)


for (i in fileNames) {
    write.table(i,paste(i,"_tables.txt",sep=""),row.names = T,sep="\t",quote=F) 
}

I want that the created files (data1_tables.txt, data2_tables.txt, data3_tables.txt) have the output from the original data1, data2, data3 variables.

ASF
  • 237
  • 1
  • 8
  • Use `get` to reference object by string: `write.table(get(i), paste(...` – Parfait Mar 27 '19 at 19:56
  • 1
    It's better not to create a much of objects with suffixes in their names. Things are much easier in R if you just collect all those objects in a named list. See this question for an example: https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames. Then you can list `lapply()` or whatever over the list. – MrFlick Mar 27 '19 at 20:10

2 Answers2

2

What is happenning is that, what you're actually writing to files are the elements from the fileNames vector (which are just strings). If you want to write any object to a file through the write functions, you need to input the object itself, not the name of the object.

#create some variables based on mtcars data
data1 <- mtcars[1:5,]
data2 <- mtcars[6:10,]
data3 <- mtcars[11:20,]

fileNames = ls(pattern="data", all.names=TRUE) 

for(i in fileNames) {

write.table(x=get(i), # The get function gets an object with a given name.
            file=paste0(i, "_tables.txt"), # paste0 is basically a paste with sep="" by default
            row.names=T, 
            sep="\t", 
            quote=F) 
}
fran496
  • 86
  • 1
  • 4
1

Change the end of your code to:

for (i in fileNames) {
write.table(eval(as.name(i)),paste(i,"_tables.txt",sep=""),row.names = T,sep="\t",quote=F) 

}

Leo Brueggeman
  • 941
  • 6
  • 5