在 R 中,是否可以将没有观察值但具有列名的空数据框写入 Excel Sheet?

In R, is it possible to write an empty data frame with no observations but with column names to an Excel Sheet?

我有 2 个数据框:一个有观察结果,一个没有观察结果。我正在使用 "xlsx" 包将数据帧写入 Excel Sheet。因为第二个数据框没有观察值,所以write.xlsx函数输出错误:

mapply(setCellValue, cells[seq_len(nrow(cells)), colIndex[ic]] 错误: 零长度输入不能与非零长度输入混合

我希望能够使用空数据框编写 Excel Sheet 并保留列名,并在没有观察结果的情况下输出。

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