【发布时间】:2018-01-04 12:01:58
【问题描述】:
我正在使用 dplyr 创建一个对象,然后我使用 xlsx 将其写入到电子表格中。
我运行以下代码:
provFundedProp <- compensationBase2014 %>%
group_by(provinciallyFunded) %>%
summarise(total=sum(fundingRaw)) %>%
mutate(percent = paste0(round(100 * total/sum(total),1), "%"))
然后我写到第一张纸上:
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")
【问题讨论】:
-
这会返回什么...
class(provFundedServiceDivision) -
至少,您可以提供
str(provFundedServiceDivision)的输出。甚至可能是traceback()在收到错误后的结果,但前提是您真的需要帮助。 ;) -
请在您的问题中输入信息。这就是允许您编辑问题的原因。
-
[注意:由于@Stedy 删除了他的答案,我已将我的评论移至此处] 我之前也遇到过这个问题。我还没有深入研究它的原因,但是 write.xlsx 可能不会超出对象的第一类。无论如何,我发现将数据框包装在
as.data.frame(my_data)中可以解决问题,大概是因为它将 tbl_df 转换回 vanilla R 数据框。