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