无法使用 R 中的 xlsx 包写入 excel 文件

Cannot write excel file using xlsx package in R

我正在使用 dplyr 创建一个对象,然后使用 xlsx 将其写入电子表格。

我运行下面的代码:

provFundedProp <- compensationBase2014 %>% 
group_by(provinciallyFunded) %>% 
summarise(total=sum(fundingRaw)) %>% 
mutate(percent = paste0(round(100 * total/sum(total),1), "%"))

然后我写到第一个sheet:

write.xlsx(provFundedProp, file="output/provFundedProp.xlsx",     
sheetName="provFundingSector")

这很好用,给了我需要的文件。

然后我运行下面的代码下降了一个级别:

provFundedServiceDivision <- compensationBase2014 %>% 
group_by(serviceDivision,provinciallyFunded) %>% 
summarise(total=sum(fundingRaw)) %>% 
mutate(percent = paste0(round(100 * total/sum(total),1), "%"))

#write to second sheet
write.xlsx(provFundedServiceDivision, file="output/provFundedSD.xlsx",   
sheetName="provFundingSD")

这给了我以下错误:

Error: cannot convert object to a data frame

我快要疯了。有谁知道到底发生了什么? 我已经在多个 wueries 上尝试过这个,但我不知道发生了什么。

class(provFundedServiceDivision) [1] "grouped_df" "tbl_df" "tbl" 
"data.frame" 

Classes ‘grouped_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 6 obs. of  4   
variables:
$ serviceDivision   : chr  "AS" "AS" "CLS" "CLS" ...
$ provinciallyFunded: chr  "NPF" "PF" "NPF" "PF" ...
$ total             : num  1.90e+06 3.97e+07 2.93e+07 5.70e+08 9.55e+07 ...
$ percent           : chr  "4.6%" "95.4%" "4.9%" "95.1%" ...
- attr(*, "vars")=List of 1
..$ : symbol serviceDivision
- attr(*, "labels")='data.frame':   3 obs. of  1 variable:
..$ serviceDivision: chr  "AS" "CLS" "GS"
..- attr(*, "vars")=List of 1
.. ..$ : symbol serviceDivision
..- attr(*, "drop")= logi TRUE
- attr(*, "indices")=List of 3
..$ : int  0 1
..$ : int  2 3
..$ : int  4 5
- attr(*, "drop")= logi TRUE
- attr(*, "group_sizes")= int  2 2 2
- attr(*, "biggest_group_size")= int 2

> traceback()
7: stop(list(message = "cannot convert object to a data frame", 
call = NULL, cppstack = NULL))
6: .Call("dplyr_cbind_all", PACKAGE = "dplyr", dots)
5: cbind_all(x)
4: bind_cols(...)
3: cbind(deparse.level, ...)
2: cbind(rownames = rownames(x), x)
1: write.xlsx(provFundedServiceDivision, file = "output/provFundedSD.xlsx", 
sheetName = "provFundingSD")

eipi10 用他的解决方案挽救了这一天!我使用了以下代码,一切正常:

write.xlsx(as.data.frame(provFundedServiceDivision), 
file="output/provFundedSD.xlsx", sheetName="provFundingSD") 

感谢大家阅读和帮助我。这是我关于堆栈溢出的第一个问题。干杯!

dplyr 链的末尾使用 ungroup()

provFundedServiceDivision <- compensationBase2014 %>% 
    group_by(serviceDivision,provinciallyFunded) %>% 
    summarise(total=sum(fundingRaw)) %>% 
    mutate(percent = paste0(round(100 * total/sum(total),1), "%")) %>%

    # Add ungroup to the end
    ungroup()

#write to second sheet
write.xlsx(provFundedServiceDivision, file="output/provFundedSD.xlsx",   
           sheetName="provFundingSD")

而不是...

class(provFundedServiceDivision)[1]
[1] "grouped_df"

你得到...

class(provFundedServiceDivision)[1]
[1] "tbl_df"