Search code examples
rloopsxlconnect

Working with objects from Global Environment in loops (R)


I am trying to fill an existing sheets in object wb (Formal class workbook XLConnect) with data frames from my Global Environment

I have a list of names of my data frames - dataframe_list, and a list of sheet names - sheetsname, both are character vectors

I have created a loop to fill corresponding sheets in wb if the name from my dataframe_list and the name of sheet sheetsname in wb are equal

My problem is, when I am running a loop, in particular data=dataframe_list[k], loop uses a name but not the data frame with corresponding name.

Hope for you help

for(k in 1:length(dataframe_list)) {
for(i in 1:length(sheetsname)) {

if (dataframe_list[k]==sheetsname[i]) {
        writeWorksheet(wb,data=dataframe_list[k],sheet=as.character(dataframe_list[k]),startRow = 49,
                       startCol = 3, header = FALSE)

}}
}

Solution

  • To return the actual data frame from its name, rather than just the name itself, use get. As in

        writeWorksheet(wb, data = get(dataframe_list[k]),
           sheet=as.character(dataframe_list[k]), startRow = 49,
           startCol = 3, header = FALSE)
    

    Note, not tested, as this was not a complete reproducible example provided