我们知道正值大于0,因此,我们可以将此条件与长度函数一起使用,以找到向量中正值的数量。例如,如果我们有一个向量x,其中包含一些正值和一些负值,并且我们想查找正值的数量,则可以使用命令length(x [x> 0])。
> x1<-rnorm(50) > x1输出结果
[1] 0.21314126 1.23449384 -1.02721325 -0.23168203 -1.36368881 -0.82416287 [7] 0.31224895 -0.90773340 0.10312288 -0.38914253 0.01196499 0.44875369 [13] 0.40820219 0.70172242 -0.23766272 -0.01023414 1.12403398 0.05837136 [19] -0.67403563 -0.26134292 0.31192384 -1.25116951 0.22115555 0.46544495 [25] 0.76567139 0.76948285 -1.42650924 0.24616899 0.18043015 1.04896235 [31] -1.84903391 1.06701870 -0.32702175 0.77332590 1.04121716 0.77967137 [37] -1.26687761 0.80629905 -0.52804923 1.31858926 0.96357328 0.19380413 [43] 0.54649834 0.70873506 -1.45764382 0.11327251 1.47389471 -1.24322096 [49] -0.24590239 -1.10458149
> length(x1[x1>0])输出结果
[1] 30
> x2<-rnorm(50) > x2输出结果
[1] -0.877360446 -2.271754557 -1.786576558 -1.067972336 0.382150798 [6] 0.842677084 -0.758538398 -1.119490974 1.896355936 0.991356448 [11] 0.248436939 0.039078483 -0.255884477 -0.107051458 0.335866428 [16] 0.014851805 0.058688431 -0.174580556 1.549126253 0.344889145 [21] -0.035863719 0.620171693 -1.517864377 -1.265375065 -1.983152664 [26] -0.239450464 0.315096209 0.061669573 -0.156187228 -1.113754030 [31] 0.373451031 -0.586700604 0.006995302 -1.219234747 0.957349339 [36] -1.651528682 0.455014272 1.386421547 1.257656374 -0.341903193 [41] -0.099243682 -0.281469501 0.594459819 0.126796982 -0.974602165 [46] -1.037023537 0.489551175 1.173538172 0.531043032 0.273650579
> length(x2[x2>0])输出结果
[1] 26
> x3<-sample(c(-5:-1,1,5),200,replace=TRUE) > x3输出结果
[1] -2 5 -5 -4 -1 -4 1 -3 1 -5 -1 -2 -3 -5 -2 1 -2 5 -4 -5 5 -4 -5 5 -3 [26] 5 -3 -5 -1 -4 -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 [181] -10 10 6 1 2 4 -1 -1 -5 -7 -5 6 -7 7 5 1 5 1 [199] 4 9
> length(x4[x4>0])输出结果
[1] 103
> x5<-sample(rnorm(10),50,replace=TRUE) > x5输出结果
[1] 0.9014379 0.6343496 1.6775916 -1.4341079 -0.1115226 -0.2008744 [7] -0.1115226 -1.1771293 -0.2008744 0.9014379 -1.5785453 -1.4341079 [13] -1.1771293 0.9014379 -0.2008744 -0.5294469 0.6343496 -1.1771293 [19] 1.6775916 -0.2008744 1.6775916 0.6343496 0.6343496 1.6775916 [25] -1.4341079 0.2165663 1.6775916 -0.2008744 -1.5785453 0.9014379 [31] 0.9014379 0.9014379 -0.5294469 1.6775916 0.2165663 -0.5294469 [37] 0.2165663 -0.1115226 -1.4341079 -0.5294469 0.6343496 -0.1115226 [43] -1.4341079 1.6775916 -1.4341079 -0.1115226 0.2165663 -0.2008744 [49] -1.1771293 -0.2008744
> length(x5[x5>0])输出结果
[1] 22