Error in x[is.na(x)] <- na.string : replacement has length zero when exporting data frame to openxlsx in R

Viewed 118

I have an issue when I try to export a data frame with the library openxlsx to an Excel. When I tried, this error happen:

openxlsx::write.xlsx(usertl_lp, file = "Mi_Exportación.xlsx")

Error in x[is.na(x)] <- na.string : replacement has length zero

3 Answers

I think you are looking for the writeData function from the same package. Check out writeFormula from the same package as well or even write_xlsx from the writexl package.

I was having a similar problem in a data frame, but, in my case, I was using the related openxlsx::writeData. The data frame was generated using sapply, with functions which could deliver errors because of the data. So, I coded to fill with NA when an error were generated. I ended up with NaN and NAs in the same column.

What worked for me is conducting the following treatment before writeData:

df[is.na(df)]<-''

so, for your problem, the following may work:

df[is.na(df)]<-''
openxlsx::write.xlsx(as.data.frame(df), file = "df.xlsx", colNames = TRUE, rowNames = FALSE, append = FALSE)
usertl_lp_clean <- usertl_lp %>% mutate(across(where(is.list), as.character))
openxlsx::write.xlsx(usertl_lp_clean, file = "Mi_Exportación.xlsx")
Related