Search code examples
rexport-to-excel

How to import output from R to an Excel File


stock_reco<- read.csv("C:\\temp\\Migration.csv")
migrate<-as.matrix(stock_reco)
title<-colnames(migrate)
dt1<-migrate[,3]
dt2<-as.Date(dt1, format= "%d/%m/%Y")
reco1<-migrate[,6]
reco<-as.matrix(reco1)
for(i in 1:4099)
{
  if((migrate[i,1]== migrate[i+1,1]) && (migrate[i,2]== migrate[i+1,2]))
    {
       k<-difftime(dt2[i+1],dt2[i],units = "days")
       if((k <=180) && (reco[i] == reco[i+1]))
       print (migrate[i,])
       print (migrate[i+1,])
       print ("----------------------------------------------------") 
    }

}

Last two print statements give my final output in the image attached below. I want the whole Final output in an excel file. So how do I import this output from R to an excel file? I want the output in this form

Comp Name Brokerage House Date CMP Target Recomendation Yes Bank Motilal Oswal 14/6/2011 294 420 Buy Yes Bank Motilal Oswal 22/9/2011 285 400 Buy

The above is just one set where if conditions are satisfied and there are several such pairs. I need all of these in an Excel sheet. When I run my code I get this in zig zag/ random form in R there are no errors in the code. Please let me know how to write this output to an excel sheet in detail. Thanks


Solution

  • @iceiceice you could try this

    stock_reco<- read.csv("C:\\temp\\Migration.csv")
    migrate<-as.matrix(stock_reco)
    title<-colnames(migrate)
    dt1<-migrate[,3]
    dt2<-as.Date(dt1, format= "%d/%m/%Y")
    reco1<-migrate[,6]
    reco<-as.matrix(reco1)
    for (i in 1:4099) {
      if((migrate[i,1]== migrate[i+1,1]) && (migrate[i,2]== migrate[i+1,2]))
        {
           k<-difftime(dt2[i+1],dt2[i],units = "days")
           if((k <=180) && (reco[i] == reco[i+1]))
           d <- rbind(d, data.frame(migrate[i,], migrate[i+1,]))
            }
        }
    
    write.csv(file=fileName, x='d')