[英]ifelse statement in mapply r
I am using mapply to find the sum of a range of indices for all cases: 我正在使用mapply查找所有情况下一系列索引的总和:
score = mapply(function(x, y, z) sum(df[x, y:z]), seq_len(nrow(df)), df$index, df$index+10)
How can I add a ifelse statement to mapply so that it only applies the function if df$index >5, else the sum is 0? 如何将ifelse语句添加到mapply,以便仅在df $ index> 5时应用该函数,否则总和为0?
This should probably work 这可能应该工作
mapply(function(x, y, z) if (y > 5) sum(df[x, y:z]) else 0,
seq_len(nrow(df)), df$index, df$index+10)
Or you could avoid if
/ else
by multiplying by (y > 5)
so index > 5
would be multiplied by 1 ( TRUE
) giving sum(df[x, y:z])
and index <= 5
would be multiplied by 0 ( FALSE
) giving 0. 或者也可以避免
if
/ else
通过乘以(y > 5)
以便index > 5
将由1(相乘TRUE
),得到sum(df[x, y:z])
和index <= 5
将由0相乘( FALSE
)给出0。
mapply(function(x, y, z) sum(df[x, y:z]) * (y > 5),
seq_len(nrow(df)), df$index, df$index+10)
Just wrap ifelse
and it should work 只是包裹
ifelse
,它应该工作
mapply(function(x, y, z) ifelse(y > 5, sum(df[x, y:z]), 0),
seq_len(nrow(df)), df$index, df$index+10)
A better option would be pre-assign based on the 'index' value to 0 for those 'index' that are less than or equal to 5. Should be more efficient 更好的选择是将小于或等于5的那些“索引”基于“索引”值预先分配为0。
i1 <- df$index > 5
score[!i1] <- 0
score[i1] <- mapply(function(x, y, z) sum(df[x, y:z]),
seq_len(nrow(df))[i1], df$index[i1], df$index[i1] + 10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.