简体   繁体   English

R:可能替代for循环吗?

[英]R: Alternative to for-loop possible?

I have a data.frame with two columns indicating the start and the end-date of a certain event, something like this: 我有一个data.frame有两列,表示某个事件的开始和结束日期,如下所示:

      [,1]  [,2]
[1,] 14260 14317
[2,] 13515 13694
[3,] 13696 13878
[4,] 13879 14060
[5,] 14061 14243
[6,] 14244 14426

I'd like to obtain a vector, containing per day (in a period from the minimum until the maximum date in this data.frame) the number of events occurring on that day. 我想获得一个向量,每天包含(在此data.frame中从最小日期到最大日期的时间段内)当天发生的事件数。

I guess a for-loop would be a logical way to solve this issue: For every two elements in a certain row, I increase the value of a pre-defined vector containing the current count of events per day with one (obviously only taking the days between [,2] and [,1] into account) 我猜一个for循环将是解决这个问题的合理方法:对于某一行中的每两个元素,我增加一个预定义向量的值,该向量包含每天的当前事件数量(显然只取一个)考虑[,2]和[,1]之间的天数

However I'd like to find a code that is more efficient to run in R, I tried to mess around with the apply-function for quite some time now but can't seem to find a feasible way to do so.. 但是我想找到一个在R中运行效率更高的代码,我试着在一段时间内使用apply-function,但似乎找不到可行的方法。

In the end, I hope to find something like this: 最后,我希望找到这样的东西:

x = [1,1,..., 2,2,2, ..., 2, 1, 1, 1]

with x[1] being the number of events occurring on the first day that is analyzed (day 13515 when considering the example above) x [1]是分析的第一天发生的事件数(考虑上述例子时的第13515天)

Thanks! 谢谢!

if test is your dataframe, then 如果test是你的数据帧,那么

create all_days vector with sequence: 使用序列创建all_days向量:

all_days <- seq( from = min(test[[1]]), to = max(test[[2]]))

and count the events for each interval: 并计算每个间隔的事件:

events_in_days <-
  sapply(all_days, function(x) {
    sum( x >= test[[1]] & x <= test[[2]] )
  })

You have your result in events_in_days . 您将结果发送到events_in_days

Maybe you want to check the <= an >= conditions (to decide whether to include the last or(and) the first day in the interval (I included both). 也许你想检查<= an >=条件(决定是否包括最后一个或(和)第一天的间隔(我包括两者)。

To check the number of days with different number of events call table : 要检查具有不同事件数的天数,请调用table

cbind(table(events_in_days))

0    1
1  853
2   58

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM