2016-07-23 3 views
0

레이블이있는 변수를 숫자 변수로 변환하는 더 간단한 방법이 있습니까?코드화 된 변수를 코드화 후 숫자로 강제 변환

다음 코드는 내 문제를 설명합니다. 저장 파일에서 중요성을 알게 된 후 모든 변수는 레이블이 지정된 변수입니다. 일부는 원래 숫자 값이며 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)