问题
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