创建一个符合条件的行数的向量

时间:2015-09-28 12:01:56

标签: r

我想创建一个包含符合我的条件的行数的矢量^ =:

leftE0 <- c(900,2000,4000,9000,15000,30000,53000,100000,160000)
rightE0 <- c(2000,4000,9000,15000,30000,53000,100000,160000,300000)

sum(datap$CF > 0 & (datap$E0.keV > leftE0[1]) & (datap$E0.keV < rightE0[1]), na.rm=TRUE)

我不明白如何将此动作矢量化。

1 个答案:

答案 0 :(得分:2)

使用cuttable

#some example data
set.seed(42)
datap <- data.frame(CF = rnorm(100), E0.keV = exp(runif(100, 0, log(4e6))))

breaks <- c(-Inf, 900,2000,4000,9000,15000,30000,53000,100000,160000, 300000, Inf)

table(cut(datap$E0.keV, breaks), datap$CF > 0)
#                  FALSE TRUE
#  (-Inf,900]         21   32
#  (900,2e+03]         6    3
#  (2e+03,4e+03]       3    3
#  (4e+03,9e+03]       6    0
#  (9e+03,1.5e+04]     1    1
#  (1.5e+04,3e+04]     0    1
#  (3e+04,5.3e+04]     1    0
#  (5.3e+04,1e+05]     2    0
#  (1e+05,1.6e+05]     1    0
#  (1.6e+05,3e+05]     2    1
#  (3e+05, Inf]        3   13