[英]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 我正在尝试使用全局环境中的数据框填充对象wb
(正式类工作簿XLConnect)中的现有工作表
I have a list of names of my data frames - dataframe_list
, and a list of sheet names - sheetsname
, both are character vectors 我有我的数据帧的名称列表- dataframe_list
,和工作表名称列表- sheetsname
,都是特征向量
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 我已经创建了一个环,以填补相应片材在wb
如果从我的名字dataframe_list
和片材的名称sheetsname
在wb
是相等
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. 我的问题是,当我运行循环时,尤其是data=dataframe_list[k]
,循环使用名称,但不使用具有相应名称的数据框。
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
. 要从其名称返回实际数据框,而不仅仅是名称本身,请使用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: XLConnect的writeWorksheet
是矢量化的,因此您可以提供data.frame
的list
和工作表名称的矢量,如下所示:
# Collect data.frames in a list
dfs <- lapply(dataframe_list, get)
writeWorksheet(wb, data = dfs, sheet = sheetnames, ...)
No need for a for loop here. 这里不需要for循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.