使用Apply来绕过循环

时间:2015-05-08 22:53:23

标签: r

我如何使用apply或其版本来使用此循环:

data<- seq(from = -100, to = 100, by = 10)
data
times<- seq(from = 25, to = 100, by=25)
for(i in 1:length(times))
{
  print(length(data[data < -times[i] | data > times[i]])/length(data))
}

我正在计算“数据”数据帧的频率表。

谢谢。

1 个答案:

答案 0 :(得分:2)

这是一个矢量化解决方案:

unname( #remove names
  rev( #reverse order
    cumsum( #cumulative sum
      rev( #reverse order
        table( #contingency table of the counts of each interval
          cut(abs(data), c(times, Inf)) #cut into intervals
          ) 
        )
      )
    )
  ) / length(data)
#[1] 0.7619048 0.4761905 0.2857143 0.0000000

请注意,data不是data.frame。