简体   繁体   中英

Automatically using the object name as file name with write.table or write.csv

Is there a way to have the object name become the file name character string when using write.table or write.csv?

In the following, a and b are vectors. I will be doing similar comparisons for many other pairs of vectors, and would like to not write out the object name as many times as I have been doing.

unique_downa<-a[!(a%in%b)]

write.csv(unique_downa,file="unique_downa.csv")

Or if anyone has a suggestion for a better way to do this whole process, I'd be happy to hear it.

The idiomatic approach is to use deparse(substitute(blah))

eg

 write.csv.named <- function(x, ...){
      fname <- sprintf('%s.csv',deparse(substitute(x)))
      write.csv(x=x, file =  fname, ...)
 }

It might be easiest to use the names of elements of a list instead of trying to use object names:

mycomparisons <-list (unique_downa = a[!(a%in%b)], unique_downb = b[!(b%in%a)])
mapply (write.csv, mycomparisons, paste (names (mycomparisons), ".csv", sep =""))

The best thing to do is probably put your vectors in a list, and then do the comparisons, the naming, and the writing out all inside the same loop, but that depends on how similar these similar comparisons are...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM