SaitoL SaitoL - 2 months ago 13
R Question

How to use write.xlsx to write the column to the specific column

get_Close <- function(i,p,f){
#read the symbol from the excel
library("readxl");
symbols <- read_excel('test1.xlsx',col_names = FALSE);
inputI <-i;
inputP <-p;
inputF <-f;
#do a for loop here
amount <-nrow(symbols);
for (i in 1:amount){
inputQ <-symbols[i,];
print(inputQ);
dataSave<-getClose(inputQ,inputI,inputP,inputF);
library(xlsx);
write.xlsx(dataSave, "output.xlsx",sheetName ="Close Price",row.names = FALSE,col.names = FALSE);
}

}


getClose is a function that could get a column of data from a url. Is there anyway to use the write.xlsx to put every column into different column in excel? Like the first dataSave to Column A in excel, and the second to B...

Answer

without having all of your initial information this is where I would start. I'm assuming getClose() is returning a vector.

get_Close <- function(i,p,f){
    #read the symbol from the excel 
    library("readxl");
    symbols <- read_excel('test1.xlsx',col_names = FALSE);
    inputI <-i;
    inputP <-p;
    inputF <-f;
    #do a for loop here 
    amount <-nrow(symbols);
    #initialize an empty list to build out all your columns
    col_list <- list()
    for (i in 1:amount){
      inputQ <-symbols[i,];
      print(inputQ);
      dataSave<-getClose(inputQ,inputI,inputP,inputF);
      col_list <- c(col_list, list(dataSave))
     }
#use do.call to turn your list into a matrix
output <- do.call(cbind, col_list)
#coherce that matrix to a dataframe
output <- as.data.frame(output)
return(output)
}
library(xlsx);
#should be ready to write output to your xlsx destination
write.xlsx(output, "output.xlsx",sheetName ="Close Price",row.names = FALSE,col.names = FALSE);