【问题标题】:mapply with zero length inputs. How to make it skip?使用零长度输入的映射。如何让它跳过?
【发布时间】:2020-08-06 14:12:41
【问题描述】:

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

# 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 次时,我一直卡住。在这种情况下,没有大小 > 8 的个体,因此 mapply() 函数不起作用。它给了我错误:

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

如果其中一个输入为零,有没有办法让 mapply() 函数什么也不做?

谢谢。

【问题讨论】:

  • 这是mapply 函数的限制。因此,避免这种情况的唯一方法是不使用mapply

标签: r apply mapply


【解决方案1】:

为什么使用mapply?这适用于普通索引。

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 2020-09-27
      • 2021-03-16
      • 1970-01-01
      • 2011-10-15
      相关资源
      最近更新 更多