2011-04-02 67 views
3

我試圖在事後爲latex'ing獲得大量的迴歸係數。然而,I'm運行到下面的問題,我無法一些值粘貼在一起成置信區間後才明白:data.frame和變量類R的變化

> str(q2) 
'data.frame': 5 obs. of 7 variables: 
$ name  : Factor w/ 5 levels "1","2",..: 1 2 3 4 5 
$ Intercept: Factor w/ 5 levels "15.4533848220452",..: 1 2 3 4 5 
$ Int.lb : Factor w/ 5 levels "14.2125590292247",..: 1 2 3 4 5 
$ Int.ub : Factor w/ 5 levels "17.1483176230248",..: 1 2 3 4 5 
$ BAC  : Factor w/ 5 levels "-0.317030740768092",..: 1 2 3 4 5 
$ Bac.lb : Factor w/ 5 levels "-0.789518593140102",..: 1 2 3 4 5 
$ Bac.ub : Factor w/ 5 levels "0.0844578956839408",..: 1 2 3 4 5 
> str(q3) 
'data.frame': 5 obs. of 2 variables: 
$ CI: Factor w/ 5 levels "(12.17,14.34)",..: 2 1 5 4 3 
$ ci: Factor w/ 5 levels "(-0.31,0.74)",..: 3 5 2 4 1 
> q4<-as.data.frame(cbind(name=q2$name,Intercept=q2$Intercept,Interecpt.95.CI=q3$CI,BAC=q2$BAC,BAC.95.CI=q3$ci)) 
> q4 
    name Intercept Interecpt.95.CI BAC BAC.95.CI 
1  1   1    2 1   3 
2  2   2    1 2   5 
3  3   3    5 3   2 
4  4   4    4 4   4 
5  5   5    3 5   1 

> str(q4) 
'data.frame': 5 obs. of 5 variables: 
$ name  : int 1 2 3 4 5 
$ Intercept  : int 1 2 3 4 5 
$ Interecpt.95.CI: int 2 1 5 4 3 
$ BAC   : int 1 2 3 4 5 
$ BAC.95.CI  : int 3 5 2 4 1 

即爲什麼q4變量突然改變?

回答

2

簡短的答案是轉換爲內部數字代碼的因素。在cbind()通話過程中它發生了:

R> set.seed(1) 
R> dat <- data.frame(A = factor(sample(1:5, 10, rep = TRUE)), 
+     B = factor(sample(100:200, 10, rep = TRUE))) 
R> head(dat) 
    A B 
1 2 120 
2 2 117 
3 3 169 
4 5 138 
5 2 177 
6 5 150 
R> str(dat) 
'data.frame': 10 obs. of 2 variables: 
$ A: Factor w/ 5 levels "1","2","3","4",..: 2 2 3 5 2 5 5 4 4 1 
$ B: Factor w/ 9 levels "117","120","138",..: 2 1 5 3 7 4 6 9 3 8 
R> cbind(name = dat$A, foo = dat$B) 
     name foo 
[1,] 2 2 
[2,] 2 1 
[3,] 3 5 
[4,] 5 3 
[5,] 2 7 
[6,] 5 4 
[7,] 5 6 
[8,] 4 9 
[9,] 4 3 
[10,] 1 8 

的原因是cbind()產生矩陣而這正是發生轉換。這將是更容易在這種情況下創建一個新的數據幀:

R> dat2 <- data.frame(name = dat$A, foo = dat$B) 
R> dat2 
    name foo 
1  2 120 
2  2 117 
3  3 169 
4  5 138 
5  2 177 
6  5 150 
7  5 172 
8  4 200 
9  4 138 
10 1 178 

而非cbind()後跟as.data.frame()對通話。

但是問題的真正根源在於數字數據存儲在q2中。這些數據是如何讀入或在R中生成的?如果讀入R,爲什麼最終成爲一個因素?通常情況下,數據在列中都是數字,R將以數值形式讀取值。如果數據列中有類似文本的內容,它將被轉換爲一個因子。所以我會嘗試解決這個問題 - 爲什麼數據在q2因素 - 因爲它可能表明讀取或生成您不知道的數據的一些問題。

+0

Thx。 q2值來自boot.ci對象,由於某種原因最終被存儲爲一個因子。沒有cbind的data.frame解決方案工作得很好。然而,什麼是什麼時候使用asbata.frame和cbind以及何時使用data.frame? – Misha 2011-04-02 14:12:22

+0

@Misha我不認爲有。你遇到了一系列問題。在這種情況下調用data.frame()來創建你想要的對象比兩個調用更有效,特別是當兩個調用正在返回你不想要的東西時更是如此。 – 2011-04-02 14:21:27

+0

感謝您的幫助。 – Misha 2011-04-02 14:26:26