在R中循环小数

时间:2014-11-13 17:11:02

标签: r loops decimal

我有一个简单的问题让我很难过。我尝试使用一个循环来计算向量中有多少个值落入bin(0,.01),(。01,。02)等等。例如(循环不起作用):< / p>

set.seed(12345)
x<- rnorm(100, 0, .05)
vec <- rep(NA, 11)

for(i in .01:.11){
vec[i] <- sum(x> i & x < (i +.01))
}

我希望这最终在每次中断之间产生一个计数向量,这样上面的输出就是:

5,9,10...

我认为这可能与索引/小数有关。感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

您的示例包含负数,因此我假设您希望使用正数来执行此操作。您应该使用cut通过设置breaks参数将矢量划分为给定的二进制位。然后使用table,您可以计算每个区间内x的频率。

## filter x 
x <- x[x>=0.01] ## EDIT here : was  x <- abs(x)
res <- table(cut(x,breaks=seq(round(min(x),2),round(max(x),2),0.01)))
## prettier output coerce to data.frame
as.data.frame(res)

#           Var1 Freq
# 1  (0.01,0.02]    5
# 2  (0.02,0.03]    9
# 3  (0.03,0.04]   10
# 4  (0.04,0.05]   10
# 5  (0.05,0.06]    4
# 6  (0.06,0.07]    0
# 7  (0.07,0.08]    5
# 8  (0.08,0.09]    2
# 9   (0.09,0.1]    5
# 10  (0.1,0.11]    4
# 11 (0.11,0.12]    1