在R中循环小数

cod*_*art 2 loops r decimal

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

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))
}
Run Code Online (Sandbox Code Playgroud)

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

5,9,10...
Run Code Online (Sandbox Code Playgroud)

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

ags*_*udy 5

您的示例包含负数,因此我假设您希望使用正数来执行此操作.您应该使用cut通过设置breaks参数将矢量划分为给定的bin .然后使用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 
Run Code Online (Sandbox Code Playgroud)