如何限制sapply函数中的计算? [英] How to limit the calculation in a sapply function?

查看:66
本文介绍了如何限制sapply函数中的计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几个星期前,我在根据另一个数据帧中的信息来计算系数时遇到问题-到最后一个问题的链接
@PoGibas提供的解决方案效果很好,但是,我必须将计算限制为在定义的时间之后,数据帧 A 中的下一个10个值。每一行。请你帮助我好吗?
我的代码看起来像@PoGibas建议的:

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])]))


推荐答案

以下代码修改了您现有的代码,因此只有前10个条目(如果存在)才被选择和求和。如果条目少于10个,则需要 na.rm = TRUE 。在这种情况下,R自动使用 NA 填充空索引。

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))

这篇关于如何限制sapply函数中的计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆