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

问题描述 投票:2回答:2

我正在使用dplyr创建一个对象,然后我使用xlsx写出一个spreadhseet。

我运行以下代码:

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")
r dplyr xlsx
2个回答
3
投票

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

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

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


3
投票

ungroup()链的末尾使用dplyr

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"
© www.soinside.com 2019 - 2024. All rights reserved.