【问题标题】:subscripted assignment ignoring NAs忽略 NA 的下标赋值
【发布时间】:2013-10-16 22:31:45
【问题描述】:

我有一个想要标准化的评分矩阵。为了做到这一点,我只想将所有负值除以最小值,将所有正值除以最大值(方便地使每个值都为正值,并且在 0 和 1 之间,矩阵中有两个)。

如果没有 NA,这会很好。

scores[scores < 0] <- scores[scores < 0] / min(scores, rm.na=T)
scores[scores > 0] <- scores[scores > 0] / max(scores, rm.na=T)
scores

我只想忽略 NA 并将它们视为 FALSE。 min 和 max 在指定时已经很好地处理了 NA,但是有没有办法让 &lt;/&gt; 也有这样的行为?

例如以下适用:

 1 NA             T T
NA  2   >  0  ==  T T
-1 -2             F F

怎么做

 1 NA             T F
NA  2   ?  0  ==  F T
-1 -2             F F

【问题讨论】:

  • 由于您的逻辑检查不包括0,您可以将所有NA 值转换为0。或使用scores[scores &lt; 0 &amp; !is.na(scores)]。
  • 啊,谢谢!所以&amp; 确实 将 NA 替换为 TRUE。不过不漂亮:scores[scores &lt; 0 &amp; !is.na(scores)] &lt;- scores[scores &lt; 0 &amp; !is.na(scores)] / min(scores, na.rm=T)
  • 当然我也不需要用保证为零的东西替换零,但我需要保留 NA :)

标签: r slice


【解决方案1】:

使用更复杂的布尔条件:

x <- scores < 0 & !is.na(scores)

scores[x] <- scores[x] / min(scores[x])

【讨论】:

    猜你喜欢
    • 2020-08-11
    • 2018-04-24
    • 1970-01-01
    • 2012-03-19
    • 2015-10-20
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多