Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 204742

Retain value from nested for loop

$
0
0

So basically I am trying the following loop:

rawData = read.csv(file = "SampleData.csv")

companySplit = split(rawData, rawData$Company)

NameOfCompany <- numeric()
DateOfOrder <- character()
WhichProducts <- numeric()


for (i in 1:length(companySplit)){


  company_DateSplit = split(companySplit[[i]], companySplit[[i]]$Date)

  for (j in 1:length(company_DateSplit)){

    WhichProducts[j] <- (paste0(company_DateSplit[[j]]$ID, collapse=","))
    DateOfOrder[j]   <- (paste0(company_DateSplit[[j]]$Date[1]))

    NameOfCompany[j] <- (paste0(companySplit[[i]]$Company[[1]]))
  }

}


df <- data.frame(NameOfCompany,DateOfOrder, WhichProducts)
write.csv(df, file = "basket.csv")

If you check basket.csv there is output for only company D. It is not writing because of nesting of for loops I guess. I am not able to get out of it.

I need exact output as basket.csv but for all companies.

Here are the CSVs:

Input Data: Link

Output of code basket.csv: Link

The output should look like this:

Company,Date, All IDs comma seperated.
e.g.
A,Jan-18,(1,2,4)
A,Feb-18,(1,4)
B,Jan-18,(2,3,4)

I'm able to get it from the above code. But Not able to save it in CSV for all A,B,C,D companies. It saves values for only company D which is the last value in looping. (check output file link)


Viewing all articles
Browse latest Browse all 204742

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>