简体   繁体   中英

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)

}}
}

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

XLConnect's writeWorksheet is vectorized, so you can provide a list of data.frame s and a vector of sheet names like so:

# Collect data.frames in a list
dfs <- lapply(dataframe_list, get)

writeWorksheet(wb, data = dfs, sheet = sheetnames, ...)

No need for a for loop here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM