How to limit the calculation in a sapply function?

泪湿孤枕 提交于 2019-12-23 03:30:09

问题


Several weeks ago I had a problem with calculating a coefficient in dependence to information from another data frame - the link to the last question. The solution provided by @PoGibas worked very well, however, I have to limit the calculation to only the 10 next values from data frame A after a defined time in each row. Could you please help me? My code looks as @PoGibas proposed:

sapply(1:length(time), function(x) sum(df1[x, which(foo >= time[x])]))

回答1:


The following code modifies your existing code so that only the first 10 entries are selected and summed, if they exist. The na.rm = TRUE is needed for cases where there may be fewer than 10 entries. In such cases, R automatically fills the "empty" indices with NA.

sapply(1:length(time), function(x) sum(df1[x, which(foo >= time[x])][1:10], na.rm = TRUE))


来源:https://stackoverflow.com/questions/47858957/how-to-limit-the-calculation-in-a-sapply-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!