Magrittr forward pipe fails to forward values into openXL::addWorksheet - “Error …: First argument must be a Workbook”

强颜欢笑 提交于 2021-02-07 20:27:14

问题


magrittr appears to be failing to pipe 'workbook' class objects into the addWorkbook function from the package openxlsx.

(Never mind why I need to use excel...eugh yuk)

For example, to write the InsectSprays dataset to an excel file in 'base' syntax:

library("openxlsx")
insect.wb <- createWorkbook()
addWorksheet(wb = insect.wb,
             sheetName = "Insect Spray")
writeData(wb = insect.wb,
          sheet = "Insect Spray",
          x= InsectSprays)

openXL(insect.wb)

Opens a temp excel file with the data.

So magrittr should

pipe a value forward into an expression or function call; something along the lines of x %>% f, rather than f(x)

But e.g.

library("openxlsx")
library("magrittr")
insect.wb <- createWorkbook()
insect.wb %>%
  addWorksheet(sheetName = "Insect Spray") %>%
  writeData(sheet = "Insect Spray",
            x= InsectSprays)

Returns

Error in writeData(., sheet = "Insect Spray", x = InsectSprays) :
First argument must be a Workbook.

But insect.wb is a workbook object:

 > insect.wb <- createWorkbook()
 > class(insect.wb)

[1] "Workbook"
attr(,"package")
[1] "openxlsx"

Which suggests that the issue is that the object isn't getting piped in...

Am I just buggering up the syntax, or is there a more interesting explanation for why this is failing?

For interest, there is no issue with forward pipe and writeData –- if we shift the use of forward-pipes until after addWorksheet, it also works fine:

insect.wb <- createWorkbook() 
addWorksheet(wb = insect.wb,
             sheetName = "Insect Spray")

insect.wb %>%
  writeData(sheet = "Insect Spray",
            x= InsectSprays)

openXL(insect.wb)

回答1:


In your command chain, writeData takes as a first input the output of insect.wb %>% addWorksheet(sheetName = "Insect Spray")

addWorksheet modifies directly the object, and doesn't return the object, so whatever you're passing to writeData is NOT a worksheet (from your comment, it's probably the number of sheets after the add).

You may use the operator %T>% and write

insect.wb %T>%
  addWorksheet(sheetName = "Insect Spray") %>%
  writeData(sheet = "Insect Spray", x= InsectSprays)

%T>%starts a new chain in the sense that the ouput of the rhs is not returned, but the lhs is returned, so then writeData takes it where %T>% left, except that insect.wb has now been modified by addWorksheet.



来源:https://stackoverflow.com/questions/44879322/magrittr-forward-pipe-fails-to-forward-values-into-openxladdworksheet-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!