2013-03-31 54 views
0

I的值有一個數據我稱之爲sam.data如下:imputting在R和STATA

dput(sam.data) 
structure(list(idn = c(1L, 2L, 3L, 4L, 5L, 6L, 66L, 62L, 7L, 
81L, 68L, 72L), n1 = c(1L, 2L, 3L, 4L, 5L, 6L, 6L, 6L, 7L, 7L, 
7L, 7L), x = c(9.95228, 11.4186, 10.3735, 10.5453, 10.7364, 9.85219, 
9.73307, 9.86304, 9.74097, 9.57359, 9.70899, 9.75185)), .Names = c("idn", 
"n1", "x"), row.names = c(NA, 12L), class = "data.frame") 

sam.data 
    idn n1  x 
1 1 1 9.95228 
2 2 2 11.41860 
3 3 3 10.37350 
4 4 4 10.54530 
5 5 5 10.73640 
6 6 6 9.85219 
7 66 6 9.73307 
8 62 6 9.86304 
9 7 7 9.74097 
10 81 7 9.57359 
11 68 7 9.70899 
12 72 7 9.75185 

對於idn不等於n1,創建一個新的變量y這需要的x對應的值到n1,否則我將它分配爲缺失。我能夠在R中生成一個緊密的解決方案。不過,我寧願在R有優雅的解決方案。另外,我還在「Stata」中尋找解決方案。

My solution in R: 
library(plyr) 
sam.data2<-ddply(sam.data,.(n1),transform, y=x[which.min(idn)]) 
sam.data2 
sam.data2 
    idn n1  x  y 
1 1 1 9.95228 9.95228 
2 2 2 11.41860 11.41860 
3 3 3 10.37350 10.37350 
4 4 4 10.54530 10.54530 
5 5 5 10.73640 10.73640 
6 6 6 9.85219 9.85219 
7 66 6 9.73307 9.85219 
8 62 6 9.86304 9.85219 
9 7 7 9.74097 9.74097 
10 81 7 9.57359 9.74097 
11 68 7 9.70899 9.74097 
12 72 7 9.75185 9.74097 

Expected output: 

    idn n1  x  y 
1 1 1 9.95228 
2 2 2 11.41860 
3 3 3 10.37350 
4 4 4 10.54530 
5 5 5 10.73640 
6 6 6 9.85219 
7 66 6 9.73307 9.85219 
8 62 6 9.86304 9.85219 
9 7 7 9.74097 
10 81 7 9.57359 9.74097 
11 68 7 9.70899 9.74097 
12 72 7 9.75185 9.74097 

回答

3

使用by從基礎包的另一種選擇。

dat$y <- unlist(by(dat,dat$n1, FUN=  
     function(x){ 
     res <- ifelse(x$idn==x$n1, 
       NA, 
       x$x[which.min(x$idn)]) 
     })) 

注意這裏的結果與期望的輸出略有不同,因爲我使用NA(數字)而不是「它是字符串」。

idn n1  x  y 
1 1 1 9.95228  NA 
2 2 2 11.41860  NA 
3 3 3 10.37350  NA 
4 4 4 10.54530  NA 
5 5 5 10.73640  NA 
6 6 6 9.85219  NA 
7 66 6 9.73307 9.85219 
8 62 6 9.86304 9.85219 
9 7 7 9.74097  NA 
10 81 7 9.57359 9.74097 
11 68 7 9.70899 9.74097 
12 72 7 9.75185 9.74097 
+0

感謝「R」解決方案的研究。我更喜歡使用NA,因爲我希望列是數字。 – Metrics

3

我不知道你想這個什麼,但簡單地使用你的輸出,你可以使它看起來像你期望通過出看到其中x等於y和與""替換它放:

sam.data2$y[sam.data2$x == sam.data2$y] <- "" 
sam.data2 

## > sam.data2 
## idn n1  x  y 
## 1 1 1 9.95228   
## 2 2 2 11.41860   
## 3 3 3 10.37350   
## 4 4 4 10.54530   
## 5 5 5 10.73640   
## 6 6 6 9.85219   
## 7 66 6 9.73307 9.85219 
## 8 62 6 9.86304 9.85219 
## 9 7 7 9.74097   
## 10 81 7 9.57359 9.74097 
## 11 68 7 9.70899 9.74097 
## 12 72 7 9.75185 9.74097 

對此有幾種方法,取決於你想要使用的方法取決於採取哪種方法。如果純粹是爲了美觀,那麼上面的內容很簡單,但現在列是字符而不是數字。

+0

謝謝泰勒。我不知道該列將是非數字的。 – Metrics

1

Stata的解決方案:

capture net install xfill, from(http://www.sealedenvelope.com/) 
bys n1: gen y2=x/(idn==n1) 
xfill y2, i(n1) 
replace y2=. if n1==idn 
+0

感謝Dimitriy提供'stata'解決方案。 – Metrics

1

Stata的代碼可能只是

sort n1, stable 
by n1: gen y2 = x[1] if idn != n1 

(這是一項經修訂的建議。)

+0

感謝Nick爲'stata'解決方案。 – Metrics

+0

@ Nick:我認爲你需要在你的解決方案中用'n1'替換'id'。然而,即使這樣也沒有給我解決方案,因爲我想。 – Metrics

+1

很抱歉誤讀你的變量名。上面修改後的代碼重現了您的示例。 –