1

I'm trying to split a csv file by column Customer.Code and write the resulting Dataframes to seperate csv files.

splittit<- function(file){

data<-read.csv(file)

data<-split(data,data$Client.Code)

x<- length(data)

for(i in x){
  custdata<- data[i] 
  custdata<- as.data.frame(custdata)
  customer<- custdata[1,18]
  customer<- as.vector(customer)
  filename<- paste(as.character(customer),".csv")
  write.csv(custdata, file= filename)
}
}

If anyone can help me as to why only the first csv file is being written i would be very grateful.

Thanks in advance

  • 7
    Classical: Make `for(i in x)` to `for(i in 1:x)` – ChrKoenig Jun 18 '15 at 14:03
  • 1
    Beat me to it :) - Spent an hour looking for that once, will never forget it. – Mike Wise Jun 18 '15 at 14:04
  • I think that `write.cv` overwrite the file. You have to improve your code in order to make the argument(s) of `write.csv` with different names. Give a look at this discussion: http://stackoverflow.com/questions/30835815/save-imported-csv-data-in-vector-r/30835924#30835924 – SabDeM Jun 18 '15 at 14:05
  • Complete beginner here so I knew it would be something little!! – Jennifer Neary Jun 18 '15 at 14:06
  • @Hav0k You should post that as an answer so that it is resolved. – nrussell Jun 18 '15 at 14:06
  • @Hav0k what a silly I've been I pointed out this mistakes several times to other users and now I failed hahaha. But maybe I am sleepy but my previous comment still holds I think. – SabDeM Jun 18 '15 at 14:07
  • @JenniferNeary Your `for (i in x)` syntax would work if you used `x <- 1:length(data)`, but the `for (i in 1:x)` style is probably more conventional in R. – nrussell Jun 18 '15 at 14:10
  • Are you sure that your code does not overwrite the file and return only the last file? in fact the name is `customer.csv` for each session of the loop and so the first will be overwrite by the second and so on... or maybe I am missing something. – SabDeM Jun 18 '15 at 14:29
  • @SabDeM it will throw an error if the file already exists. And to your point, an overwrite error will happen if `custdata[1,18]` is the same for multiple files. – Pierre L Jun 18 '15 at 15:09
  • btw Jennifer this mistake has happened to everyone. No worries – Pierre L Jun 18 '15 at 15:10

1 Answers1

5

You defined:

x<- length(data)

which gives you a integer. However, in your for loop you don't want to iterate over a single integer, but over the whole range from 1:x. Therefore change for(i in x) to for (i in 1:x)

ChrKoenig
  • 901
  • 1
  • 9
  • 23