2016-07-23 47 views
0

在避風港或標記包中是否存在將標記變量變爲數字變量的更簡單的方法?在記錄之後將變量強制標記爲數字

以下代碼說明了我的問題。從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) 
+0

如果你有規律的數值變量,你可以很容易地將98和99改爲NA。爲什麼不把必要的列轉換爲數字,然後在設置完所有內容後擔心特定的數字? –

+1

既然你說你必須強迫數字,我認爲'ces $ PES15_74'是一個字符?那麼你可以嘗試'type.convert(c(1:5,'98','99'),na.strings = c('98','99'))' – rawr

回答

0

你可以試試我的包裝expss。但它具有稍微不同的「標記」類的實現,所以在下面的代碼中有轉換(或者可以使用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) 
相關問題