2017-07-28 88 views
0

在下面的示例中,我想提取NA作爲級別,並將其顯示在表中,就像其他級別一樣。 levels()函數不適用於NA值。有沒有其他方法可以解決這個問題?將NA分配給表名

n=1000 
comorbid<-sample(c(rep("diabetes",2), 
    rep("hypertension",5), 
    "cirrhosis","stroke","heartfailure", 
    "renalfailure",rep("COPD",3)), 
    n, 
    replace=T) 
comorbid[sample(1:n,50)]<-NA 
mort<-sample(c(rep("alive",4), 
"dead"),n,replace=T) 
table.cat<-data.frame(matrix(rep(999,7),nrow=1)) 
table<-table(comorbid,useNA="always") 
per<-prop.table(table) 
table.sub<-table(comorbid,mort,useNA="always") 
per.sub<-prop.table(table.sub,2) 
p<-tryCatch({#using fisher's test when scarce data 
     chisq.test(table.sub)$p.value 
    }, warning = function(w) { 
     fisher.test(table.sub, 
     workspace = 10e7)$p.value 
    }) 
frame<-data.frame(No.tot=as.data.frame(table)[,"Freq"], 
    per.tot=as.data.frame(per)[,"Freq"], 
    No.1=as.data.frame.matrix(table.sub)[,"alive"], 
    per.1=as.data.frame.matrix(per.sub)[,"alive"], 
    No.2=as.data.frame.matrix(table.sub)[,"dead"], 
    per.2=as.data.frame.matrix(per.sub)[,"dead"], 
    p=p) 
rownames(frame)<-paste("comorbid",levels(comorbid),sep="_") 

回答

0

levels()適用於NA值。然而,levels()要求的是因子(或具有levels屬性的任何東西)。根據你的代碼,comorbid是一個字符向量:

> class(comorbid) 
[1] "character" 

如果你強迫comorbid一個因素更改默認設置,以便NA s爲從因子水平排除在外,你所期望的行爲:

fcomorbid <- factor(comorbid, exclude = NULL) 

levels(fcomorbid) 
paste("comorbid", levels(fcomorbid), sep = "_") 

> levels(fcomorbid) 
[1] "cirrhosis" "COPD"   "diabetes"  "heartfailure" "hypertension" 
[6] "renalfailure" "stroke"  NA    
> paste("comorbid", levels(fcomorbid), sep = "_") 
[1] "comorbid_cirrhosis" "comorbid_COPD"   "comorbid_diabetes"  
[4] "comorbid_heartfailure" "comorbid_hypertension" "comorbid_renalfailure" 
[7] "comorbid_stroke"  "comorbid_NA" 

要完成你的榜樣,然後

rownames(frame) <- paste("comorbid", levels(fcomorbid), sep = "_") 

我們有

> frame 
         No.tot per.tot No.1  per.1 No.2  per.2   p 
comorbid_cirrhosis  69 0.069 57 0.07011070 12 0.06417112 0.3108409 
comorbid_COPD   209 0.209 172 0.21156212 37 0.19786096 0.3108409 
comorbid_diabetes  128 0.128 101 0.12423124 27 0.14438503 0.3108409 
comorbid_heartfailure  57 0.057 45 0.05535055 12 0.06417112 0.3108409 
comorbid_hypertension 334 0.334 267 0.32841328 67 0.35828877 0.3108409 
comorbid_renalfailure  78 0.078 61 0.07503075 17 0.09090909 0.3108409 
comorbid_stroke   75 0.075 63 0.07749077 12 0.06417112 0.3108409 
comorbid_NA    50 0.050 47 0.05781058 3 0.01604278 0.3108409 
+0

我不會說它的作品「很好」:)。 'levels(my_vec)< - c(NA,「a」)'具有奇怪的行爲,NA級別將被諸如'rbind'等函數放棄。看到這個問題有關它:https://stackoverflow.com/questions/45216532/how-can-i-keep-na-when-i-change-levels –

+0

我的結論到目前爲止,NA水平應該使用非常本地時你真的知道你在做什麼,否則考慮用普通級別替換它們,例如「NA」或「未知」 –

+0

@Moody_Mudskipper給出'levels()'聲明的目的是「提供[s]訪問級別變量的屬性「。我會說這個工程*很好*。您正在討論替換函數變量'levels < - ()',並在'?levels'中記錄了行爲。 –