首页 > 解决方案 > 在 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]] 中的错误:零长度输入不能与非零长度的输入混合

标签: rxlsx

解决方案


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")

推荐阅读