r - 在 R 中,是否可以将没有观察但具有列名的空数据框写入 Excel 工作表?
问题描述
我有 2 个数据框:一个有观察结果,一个没有观察结果。我正在使用“xlsx”包将数据框写入 Excel 表。因为第二个数据帧没有观测值,所以 write.xlsx 函数输出错误:
mapply(setCellValue, cells[seq_len(nrow(cells)), colIndex[ic]] 中的错误:零长度输入不能与非零长度的输入混合
我希望能够使用空数据框编写 Excel 工作表并保留列名,并在没有观察的情况下输出。
library(xlsx)
nonemptydf <- data.frame("SN" = 1:2,
"Age" = c(21, 15),
"Name" = c("John", "Jane"))
emptydf <- data.frame("SN" = numeric(),
"Age" = numeric(),
"Name" = character())
write.xlsx(nonemptydf,
"Test.xlsx",
sheetName = "Not empty")
#The code below won't work because emptydf has no observations
write.xlsx(emptydf,
"Test.xlsx",
sheetName = "Empty",
append = TRUE)
来自 xlsx 函数的错误:mapply(setCellValue, cells[seq_len(nrow(cells)), colIndex[ic]] 中的错误:零长度输入不能与非零长度的输入混合
解决方案
Tibbles 比“data.frame”对象具有更多的灵活性和功能。特别是,您可以使用 tribble() 函数直接在调用中指定列名。
# load the packages
library(tidyverse) # provides the tribble() function
library(zip) # helps zip the dataset that will be exported to R
library(rio) # better export package than xlsx
# create your tibble
d <- tribble(
~SN, ~Age, ~Name
)
# convert to data.frame (if you'd prefer this class); it's not necessary though...
d <- as.data.frame(d)
# export your data frame as an Excel-compatible file
export(d, "data.xlsx")
推荐阅读
- c++ - C ++ - Boost streambuf放气的行为不一致?
- css - 如何使用 CSS 创建一个带有凹槽的矩形?
- sql - Oracle XMLTYPE 根据条件从节点中提取第一行值
- windows - 如何将我的 AWS CLI 驱动器从 H 更改为 C
- python - 使用 Python ElementTree 在另一个 xml 文件的节点中插入一个 xml 文件
- amazon-web-services - Terraform 从 TG 路由表和 TG 附件 vpns 创建 map/dict 以在资源 aws_ec2_transit_gateway_route_table_association 中引用
- macos - 使用 Mac Big Sur 安装 upx
- android - 自定义视图未在 BottomSheetDialogFragment 中绘制,有时在无效后调用 onSizeChanged
- c# - 积分系统无法正常工作 Unity(Visual Studio C#)
- c# - Power BI embed API 访问令牌请求通过 Postman 而不是通过代码工作