如何在 R 数据框列中选择正值?
我们知道正值大于
df1$x[which(df1$x>0)]
示例 1
set.seed(254) x<−rnorm(20) df1<−data.frame(x) df1
输出
x 1 −0.2581511 2 1.5986312 3 0.1347109 4 −0.4816860 5 1.0202752 6 0.2968755 7 −0.1281462 8 1.6107106 9 −1.9545718 10 0.3993334 11 −0.4458160 12 0.5535872 13 1.6401329 14 −0.2909519 15 −0.1275311 16 0.5795695 17 −0.7438926 18 1.2381494 19 0.3837225 20 0.9689413
示例
df1$x[which(df1$x>=0)]
输出
[1] 1.5986312 0.1347109 1.0202752 0.2968755 1.6107106 0.3993334 0.5535872 [8] 1.6401329 0.5795695 1.2381494 0.3837225 0.9689413
示例 2
y<−rnorm(20) df2<−data.frame(y) df2
输出
y 1 1.53798786 2 −0.85463326 3 2.39444451 4 0.82559418 5 −2.22197322 6 −1.04243823 7 −0.04693054 8 −0.68691236 9 −1.63040923 10 −1.42408865 11 1.79834289 12 −0.43978051 13 0.47706345 14 0.59884206 15 −0.69136846 16 0.22906493 17 −0.26332146 18 0.29536361 19 −1.24096107 20 0.04963628
示例
df2$y[which(df2$y>=0)]
输出
[1] 1.53798786 2.39444451 0.82559418 1.79834289 0.47706345 0.59884206 0.22906493 [8] 0.29536361 0.04963628
示例 3
z<−sample(−2:2,20,replace=TRUE) df3<−data.frame(z) df3
输出
z 1 −2 2 2 3 0 4 −2 5 −2 6 −2 7 0 8 −2 9 −1 10 −2 11 0 12 −2 13 0 14 2 15 1 16 1 17 1 18 0 19 1 20 −2
示例
df3$z[which(df3$z>=0)]
输出
[1] 2 0 0 0 0 2 1 1 1 0 1
广告