Jennifer Neary
Jennifer Neary

Reputation: 63

R for loop only completing first iteration

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

Upvotes: 2

Views: 3589

Answers (1)

ChrKoenig
ChrKoenig

Reputation: 973

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)

Upvotes: 7

Related Questions