使用零长度输入进行映射。如何让它跳过?

mapply with zero length inputs. How to make it skip?

我有 2 个独立的数据集,它们具有相同个体的品质:位置和大小。位置将根据大小每小时更改一次。尺寸也会每小时变化一次,但在这个代表中没有。无论如何,我在一个循环中执行此操作,该循环每小时使用 apply() 函数迭代一次以更改矩阵的下一列。当 none 个人在该循环迭代期间满足这些条件时,我需要帮助使这些功能正常工作。

# here is a matrix of positions. the first column is the starting position,
# and this will change throughout, so second column is empty for now.
position <- cbind(c(10,20,10,20,10),c(NA,NA,NA,NA,NA)) 

# size of individuals. position in next column should change depending on size,
# such that small individuals (size < 5) will move up 5 positions, 
# and large individuals (> 8) will move down 7 positions. 
size <- c(2,2,3,8,8)

# for small individuals, add 5 to make next position
position[,2][ size < 5] <- mapply(sum,position[,1][size<5],5)  

# for large individuals, subtract 7 to make next position
position[,2][ size > 8 ] <- mapply(sum,position[,1][size > 8],-7)

当条件出现 0 次时,我总是卡住。在这种情况下,没有 size > 8 的个体,所以 mapply() 函数不起作用。它给了我错误:

  zero-length inputs cannot be mixed with those of non-zero length

有没有办法让 mapply() 函数在其中一个输入为零时什么都不做?

谢谢。

为什么要使用mapply?这在正常索引下工作得很好。

position[size < 5,2] <- position[size < 5,1] + 5
position[size > 8,2] <- position[size > 8,1] - 7

我们可以创建一个索引来传递 vector 个值并一步完成(如果有多个条件)

i1 <- 1 + 2 * (size < 5) + 4 * (size > 8)
position[,2] <- position[,1] + c(5, -7)[match(i1, unique(i1))]