【问题标题】:R: Change Vector based on range conditionsR:根据范围条件改变向量
【发布时间】:2014-01-25 00:46:15
【问题描述】:

我想根据条件更改矢量元素。 例如:我有一个向量v<-c(-3,5,-1,7,8,1,10,11),我想生成向量(-1,1,0,1,1,0,1,1) 条件是

if the element is <-1 then set -1
if the element is >1 then set 1
otherwise 0

我可以通过使用一系列ifelse 语句来实现这一点:

 v<-c(-3,5,-1,7,8,1,10,11)
    res<-rep(0,8)
    res<-ifelse(v<1,-1,res)
    res<-ifelse(v>1,1,res)

我认为应该有一个更优雅和紧凑的方式来做到这一点。 有什么建议吗?

谢谢

【问题讨论】:

标签: r if-statement vector range conditional-statements


【解决方案1】:
sign(v) * (abs(v) > 1)
# [1] -1  1  0  1  1  0  1  1

【讨论】:

    【解决方案2】:
    v[v >= -1 & v <= 1] = 0
    v = sign(v)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多