1

在 Haven 或标签包中是否有更简单的方法将标签变量转换为数值变量?

以下代码说明了我的问题。在重要的 sav 文件之后,每个变量都是一个标记变量。有些最初是数字变量,其中 98 和 99 作为缺失值。所以我必须重新编码那些设置为 NA,但是我必须用 as.numeric() 将重新编码的变量强制为数字

有没有更简单的方法来做到这一点?

#Load libraries
library(devtools)
library(dplyr)
library(car)
#Install package with data
install_github('sjkiss/LSIRM')
#Load library
library(LSIRM)
#Loda dataset
data(ces)
#show variable of interest
table(ces$PES15_74)
#Get variable labels
variable_labels<-lapply(ces, function(x) attr(x, 'label'))
#Get value labels
value_labels<-lapply(ces, function(x) attr(x, 'labels'))
#Show class of variable of interest
class(ces$PES15_74)
#show variable and value labels
ces$PES15_74 
attr(ces$PES15_74, 'labels') #Note 98 and 99 should be missing values 
#Show mean
mean(ces$PES15_74, na.rm=T)
#Recode out missing values
ces$tv<-recode(ces$PES15_74, "98:99=NA")
#Show class
class(ces$tv)
#Try with as.factor.result=F
ces$tv2<-recode(ces$PES15_74, "98:99=NA", as.factor.result=F)
#show class
class(ces$tv2)
#coerce to numeric
ces$tv<-as.numeric(ces$tv)
#show mean after coercion
mean(ces$tv, na.rm=T)
#show mean uncoerced
mean(ces$PES15_74, na.rm=T)
4

1 回答 1

2

你可以试试我的包expss。但它对“labelled”类的实现略有不同,因此在下面的代码中有转换(或者您可以使用 expss::read_spss 读取 *.sav 文件)。

library(LSIRM)
data(ces)
library(expss)

### change class "labelled" to c("labelled", "numeric")
for (each in colnames(ces)){
    if ("labelled" %in% class(ces[[each]])){
        class(ces[[each]]) = c("labelled", "numeric")
    }
}

### calculations
fre(ces$PES15_74)
ces$tv = if_val(ces$PES15_74, 98:99 ~ NA)
fre(ces$tv)
cro(ces$PES15_74, ces$tv)
mean_col(ces$tv)
于 2016-07-23T20:52:02.533 回答