2016-04-10 99 views
-2

帮助寻求任何人。R创建满足条件的变量

我有一个家庭调查数据集名为h2004,并希望创建一个变量等于另一个变量满足某些条件。我在这里提出了一个观察样本。

cq15  expen 
10  0.4616136 
10  1.538712 
11  2.308068 
11  0.384678 
12  2.576797822 
12  5.5393632 
13  5.4624276 
14  2.6158104 
14  20.157127 

,我尝试下面的命令:

h2004$crops[h2004$cq15>=12 & h2004$cq15<=14]=h2004$expen 

,这会产生错误的结果在R作为我知道,从使用的Stata正确的结果。在原始数据集中,上述命令即使在cq15<12处取值为'费用',并将其替换为cq15>=12 & cq15<=14

我也尝试过使用dplyr的正确子集数据框的过滤器选项,但不知道如何将其应用于特定变量。

fil<- filter(h2004, cq15>=12 & cq15<=14)

我觉得我的子集(cq15>=12 & cq15<=14)是错误的。请指教。谢谢

回答

0

问题出在命令中。当执行命令时,发出以下警告消息:

Warning message: 
    In h2004$crops[h2004$cq15 >= 12 & h2004$cq15 <= 14] = h2004$expen : 
    number of items to replace is not a multiple of replacement length 

这样做的原因是,该命令的LHS选择满足条件H2004 $ cq15> = 12 & H2004 $ cq15 < = 14元件而在RHS上,则给出完整的矢量h2004 $ expensive,导致长度不匹配。

解决方案:

> h2004$crops[h2004$cq15>=12 & h2004$cq15<=14]=h2004$expen[h2004$cq15>=12 & h2004$cq15<=14] 

> h2004 
    cq15  expen  crops 
1 10 0.4616136  NA 
2 10 1.5387120  NA 
3 11 2.3080680  NA 
4 11 0.3846780  NA 
5 12 2.5767978 2.576798 
6 12 5.5393632 5.539363 
7 13 5.4624276 5.462428 
8 14 2.6158104 2.615810 
9 14 20.1571270 20.157127 

或者:

> indices <- which(h2004$cq15>=12 & h2004$cq15<=14) 
> h2004$crops[indices] = h2004$expen[indices] 
> h2004 
    cq15  expen  crops 
1 10 0.4616136  NA 
2 10 1.5387120  NA 
3 11 2.3080680  NA 
4 11 0.3846780  NA 
5 12 2.5767978 2.576798 
6 12 5.5393632 5.539363 
7 13 5.4624276 5.462428 
8 14 2.6158104 2.615810 
9 14 20.1571270 20.157127 
+1

非常感谢。这工作完美。 –