csmontt
csmontt

Reputation: 624

R error when using write.xlsx with an object created with functions of 'dplyr'

I´m having a problem when trying to write a data frame to an excel file using the function write.xlsx from the xlsx package. Though the problem only appears when the data frame was created with functions from the dplyr package. When I use base functions, there is no problem. Below is a minimal example.

First, the sample data:

library(dplyr)
library(xlsx)
month <- c('Julio','Diciembre','Diciembre','Agosto','Noviembre',
         'Diciembre', 'Junio','Septiembre','Agosto','Julio')

irrelevant_column <- rep(1,10)

df <- as.data.frame(cbind(irrelevant_column, month)) 

As I said, when I use base functions there is no problem:

month1  <- table(df$month, df$irrelevant_column)
month1  <- prop.table(month1  , 2)
month1  <- as.data.frame.matrix(month1  )
write.xlsx(month1 ,  file="month1.xlsx")

No error appears, but when I create a similar data frame with 'dplyr':

month2<- count(df, month)
month2<- mutate(month2, porc = n / sum(month2[, 2]))
month2<- as.data.frame.matrix(month2)
write.xlsx(month2,  file="month2.xlsx")

The following error message appears:

Error in .jcall(cell, "V", "setCellValue", value) : 
  method setCellValue with signature ([Ljava/lang/String;)V not found
In addition: Warning message:
In if (is.na(value)) { :
  the condition has length > 1 and only the first element will be used

Is there a solution for this, or is it that xlsx is not compatible with dplyr?

Upvotes: 3

Views: 3528

Answers (2)

Gustavo Barbosa
Gustavo Barbosa

Reputation: 11

I had the same problem and fixed with this solving using

write.xlsx(as.data.frame(dataset), "name.xlsx")

Upvotes: 1

karistaeh
karistaeh

Reputation: 31

ran into this issue and solved it using as.data.frame() to designate the tibble output from group_by() %>% summarize() as a df.

Upvotes: 2

Related Questions