karyn-h
karyn-h

Reputation: 133

write.csv: file name depends on an evaluation

I have a large dataset with 9,000 entries. I hope to split it into subfiles and name them as 1-1000, 1001 - 2000 etc.

d <- split(df,rep(1:9,each=1000))

lapply(names(d),
       function(x){
         start <- x*1000-1000 + 1
         end <- x*1000
         
         write.csv(d[[x]], file = paste0("directory_name/", start, "-", "end",".csv"),
                             row.names = FALSE)}) 

Using the code above, I get an error saying "Error: unexpected '}' in file = paste0("directory_name/", start, "-", end,".csv"), row.names = FALSE)". I am not sure how to solve this, could anyone help me? Thank you.

Upvotes: 0

Views: 57

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388817

Names are stored as characters so if you want to perform any mathematical calculation on them you need to change them to numeric. You can try this -

d <- split(df,rep(1:9,each=1000))

lapply(names(d),function(x) {
     x1 <- as.numeric(x)
     start <- x1*1000-1000 + 1
     end <- x1*1000
     write.csv(d[[x]], sprintf("directory_name/%d-%d.csv", start, end),row.names = FALSE)
}) 

Upvotes: 2

Related Questions