在避风港或带标签的包中,有没有更简单的方法将带标签的变量转换为数值变量?
下面的代码说明了我的问题。从一个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)发布于 2016-07-24 04:52:03
你可以试试我的包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)https://stackoverflow.com/questions/38545284
复制相似问题