0

我正在尝试计算落在 1000 个窗口内的条目,问题是我正在使用 for 循环,这使得需要执行的操作数量非常大(我对 R 相当陌生)并且我得到了的边界错误。我知道必须有更好的方法来做到这一点。

文件(警告文件超过 100mb):bamDF.txt

采用:

dget(file="bamDF.txt")

脚本:

attach(bamDF)
out <- matrix(0,1,ceiling((max(pos, na.rm=TRUE)-min(pos, na.rm=TRUE))/interval))
interval <- 1000
for(q in 1:nrow(bamDF)){
  for(z in 1:ceiling((max(pos, na.rm=TRUE)-min(pos, na.rm=TRUE))/interval)){
    if(min(pos, na.rm=TRUE)+interval*(z-1)<pos[q]&&pos[q]<(min(pos, na.rm=TRUE)+interval*(z))){
      out[z,] <- out[z,]+1;


    }

  }


}
detach(bamDF)
4

2 回答 2

1

您可以使用该cut功能

# set the seed to get a reproducible example
set.seed(12345)

min.val <- 0
max.val <- 5000
num.val <- 10000
# Generate some random values
values <- sample(min.val:max.val, num.val, replace=T)

interval <- 1000
num.split <- ceiling((max.val - min.val)/interval)+1

# Use cut to split the data. 
# You can set labels=FALSE if you want the group number 
# rather than the interval
groups <- cut(values, seq(min.val, max.val, length.out=num.split))

# Count the elements in each group
res <- table(groups)

res将包含:

groups
    (0,1e+03] (1e+03,2e+03] (2e+03,3e+03] (3e+03,4e+03] (4e+03,5e+03] 
         1987          1974          2054          2000          1984 

同样,您可以只使用以下hist功能:

 h <- hist(values, 10) # 10 bins

或者

 h <- hist(values, seq(min.val, max.val, length.out=num.split))

h$counts包含计数。plot=NULL如果您不想绘制结果,请使用。

于 2013-06-14T15:01:12.587 回答
0
grps <- seq(min(pos), max(pos), by= 1000)
counts <- table( findInterval( pos, c(grps, Inf) ) )
names(counts) <- grps
于 2013-06-14T16:04:22.800 回答