无法使用 foreign 或 haven 将 dataframe 转换为 Stata

Can't convert dataframe to Stata using foreign or haven

我有一个数据框,我正在尝试将其另存为 stata .dta 文件。 我尝试了 haven 和 foreign 包裹,但我收到以下错误:

write_dta(df,"C:/Users/../df.dta")

我得到一个错误:

Error in write_dta_(data, normalizePath(path, mustWork = FALSE), version = stata_file_format(version),  : Variables of type list not supported yet

同国外包:

write.dta(df,"C:/Users/../df.dta")

write.dta(data = df,file = "C:/Users/../df.dta")

错误:

Error in write.dta(df, "C:/users/../df.dta") : 
  unknown data type

但是当我检查 df 是否确实是一个数据帧时,我得到了 TRUE:

is.data.frame(df)
[1] TRUE

我想到了使用 writexl 库并将其保存为 xlsx,然后将其导入 Stata:

write_xlsx(df,"C:/Users/../df.xlsx")

但在生成的 excel 文件中,所有计数列(请参阅附图)都是空的。所以 xlsx 文件中只填写了 1 到 4 列。所以我想知道我的计数列是否有问题。

由于我无法以简单的方式复制我的数据,所以我附上了一张图片:

根据@user20650 的建议,我 运行 以下代码:

dput(tc[1:5, 3:6])

结果如下:

structure(list(filing_type = c("10-K", "10-K", "10-K", "10-K", 
"10-K/A"), year = c("2014", "2013", "2012", "2011", "2010"), 
    Alabama_count = list(mktg_10k14.htm = 0L, mktg_10k.htm = 0L, 
        mktg_10k.htm = 0L, mktg_10k.htm = 0L, mktg_10ka.htm = 0L), 
    Alaska_count = list(mktg_10k14.htm = 0L, mktg_10k.htm = 0L, 
        mktg_10k.htm = 0L, mktg_10k.htm = 0L, mktg_10ka.htm = 0L)), row.names = c(NA, 
5L), class = "data.frame")

正如@Andrew 所建议的,我的计数列都是列表而不是数据框。

好的,根据这里的评论是一个解决方案(unlist 列)。我还包括了对列表列进行标识的检查:

# Reprodible example set-up
mtcars <- datasets::mtcars

mtcars$mpg <- as.list(mtcars$mpg) # manually adding a list column
haven::write_dta(mtcars, "path.dta") # same error
Error in write_dta_(data, normalizePath(path, mustWork = FALSE), version = stata_file_format(version),  : 
  Variables of type list not supported yet

# ID the list column
sapply(mtcars, is.list) # T/F vector
  mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb 
 TRUE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE 

# or
# sapply(mtcars, typeof) # returns column types

如何修复(根据评论)

idx <- sapply(mtcars, is.list) # create an index of your list columns
mtcars[idx] <- lapply(mtcars[idx], unlist) # unlisting the list columns (selected by idx)
    
    
any(sapply(mtcars, is.list)) # are any columns type list
[1] FALSE