我一直在使用hmisc包中的一个名为haven_labelled (有时只是labelled)的类。它的目的是从Stata .dta数据集导入列标签。当试图在dataframe上使用plm时,我得到了以下错误:
Error in as.data.frame.default(x[[i]], optional = TRUE) :
cannot coerce class ‘c("pseries", "haven_labelled")’ to a data.frame课程如下:
> class(actualdataset)
[1] "pdata.frame" "data.frame"
> class(actualdataset$examplevar)
[1] "pseries" "haven_labelled"因此,我想从这个数据库中删除haven_labelled类。很遗憾,我未能重现这一错误。我认为这与我的var有关,因为我的actualdataset是双类的,其中包括有haven_labelled。请参阅下面的示例数据集。
library(data.table)
library(plm)
library(Hmisc)
set.seed(1)
DT <- data.table(panelID = sample(50,50), # Creates a panel ID
Country = c(rep("A",30),rep("B",50), rep("C",20)),
some_NA = sample(0:5, 6),
some_NA_factor = sample(0:5, 6),
Group = c(rep(1,20),rep(2,20),rep(3,20),rep(4,20),rep(5,20)),
Time = rep(seq(as.Date("2010-01-03"), length=20, by="1 month") - 1,5),
norm = round(runif(100)/10,2),
Income = sample(100,100),
Happiness = sample(10,10),
Sex = round(rnorm(10,0.75,0.3),2),
Age = round(rnorm(10,0.75,0.3),2),
Educ = round(rnorm(10,0.75,0.3),2))
DT [, uniqueID := .I] # Creates a unique ID
DT[DT == 0] <- NA # https://stackoverflow.com/questions/11036989/replace-all-0-values-to-na
DT$some_NA_factor <- factor(DT$some_NA_factor)
labels <- data.table::fread("Varcode Variables
panelID a
Country b
Group c
Time d
norm e
Income f
Happiness g
Sex h
Age i
Educ j
uniqueID k
", header = TRUE)
for (i in seq_len(ncol(DT))) {
label(DT[[i]]) <- labels$Variables[match(names(DT)[i], labels$Varcode)]
}
DTp <- plm::pdata.frame(DT, index= c("panelID", "Time"))
result <- plm(Happiness ~ Income, data=DTp, model="within")
> class(DTp)
[1] "pdata.frame" "data.frame"
> class(DTp$Income)
[1] "pseries" "labelled" "integer" 有什么建议吗?
编辑:我在想一些事情如下:
for for (i in seq_len(ncol(DT)) {
if (sapply(DT, function(x) class(x)[1L]) == "haven_labelled") {
attr(DT[,i],"class[1L]") <- "integer"
}
}编辑2:在应用plm时,答案可以防止任何错误。遗憾的是,所有的coefficients,standard errors都是零。P-values和t-values是NA。我不知道是什么原因造成的。
发布于 2019-08-19 09:46:12
此解决方案基于提供的数据集DTp,根据原始数据集更改labelled和labelled_ch。
for (i in seq_len(ncol(DTp))) {
if (any(class(DTp[,i]) == "labelled")) {
#browser()
ind = which(class(DTp[,i])=="labelled")
attr(DTp[,i],"class")[ind] <- "labelled_ch"
}
}https://stackoverflow.com/questions/57543054
复制相似问题