2013-03-31 58 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

很抱歉误读你的变量名。上面修改后的代码重现了您的示例。 –