0

I am looking for an elegant way to insert character (name) into directory and create .csv file. I found one possible solution, however I am looking another without "replacing" but "inserting" text between specific charaktects.

#lets start
    df <-data.frame()
    name <- c("John Johnson")
    dir <- c("C:/Users/uzytkownik/Desktop/.csv")
#how to insert "name" vector between "Desktop/" and "." to get:
    dir <- c("C:/Users/uzytkownik/Desktop/John Johnson.csv")
    write.csv(df, file=dir)
#???

#I found the answer but it is not very elegant in my opinion
    library(qdapRegex)
    dir2 <- c("C:/Users/uzytkownik/Desktop/ab.csv")
    dir2<-rm_between(dir2,'a','b', replacement = name)
> dir2
[1] "C:/Users/uzytkownik/Desktop/John Johnson.csv"
    write.csv(df, file=dir2)
Mikołaj
  • 385
  • 4
  • 17

4 Answers4

3

I like sprintf syntax for "fill-in-the-blank" style string construction:

name <- c("John Johnson")
sprintf("C:/Users/uzytkownik/Desktop/%s.csv", name)
# [1] "C:/Users/uzytkownik/Desktop/John Johnson.csv"

Another option, if you can't put the %s in the directory string, is to use sub. This is replacing, but it replaces .csv with <name>.csv.

dir <- c("C:/Users/uzytkownik/Desktop/.csv")
sub(".csv", paste0(name, ".csv"), dir, fixed = TRUE)
# [1] "C:/Users/uzytkownik/Desktop/John Johnson.csv"
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
1

This should get you what you need.

dir <- "C:/Users/uzytkownik/Desktop/.csv"
name <- "joe depp"

dirsplit <- strsplit(dir,"\\/\\.")
paste0(dirsplit[[1]][1],"/",name,".",dirsplit[[1]][2])

[1] "C:/Users/uzytkownik/Desktop/joe depp.csv"

Adam Wheeler
  • 393
  • 1
  • 11
1

I find that paste0() is the way to go, so long as you store your directory and extension separately:

path <- "some/path/"
file <- "file"
ext  <- ".csv"

write.csv(myobj, file = paste0(path, file, ext))

For those unfamiliar, paste0() is shorthand for paste( , sep="").

DanY
  • 5,920
  • 1
  • 13
  • 33
0

Let’s suppose you have list with the desired names for some data structures you want to save, for instance:

names = [“file_1”, “file_2”, “file_3”]

Now, you want to update the path in which you are going to save your files adding the name plus the extension,

path = “/Users/Documents/Test_Folder/”
extension = “.csv”

A simple way to achieve it is using paste() to create the full path as input for write.csv() inside a lapply, as follows:

lapply(names, function(x) {
    write.csv(x = data, 
              file = paste(path, x, extension))
     }
)

The good thing of this approach is you can iterate on your list which contain the names of your files and the final path will be updated automatically. One possible extension is to define a list with extensions and update the path accordingly.

Jorge Quintana
  • 801
  • 6
  • 8