【问题标题】:Increasing elements in vector in R [duplicate]在R中增加向量中的元素[重复]
【发布时间】:2021-01-24 23:29:29
【问题描述】:

我有一个向量,我想在另一个向量的基础上增加元素。
如何在无需手动输入的情况下增加向量中的元素? 我想使用这两个向量

NumberofTimes<-c(4,1,2,3)
Spread<-c(0.060,0.170,0.140,0.070)
```
I.e. I want a vector with 4 of the 0.060, 1 of the 0.170, 2 of the 0.140, etc.
Instead of writing: 
  
```
Spread<-c(0.060,0.060,0.060,0.060,0.170,0.140,0.140,0.070,0.070,0.070)
```

【问题讨论】:

    标签: r vector resize


    【解决方案1】:

    带有 times 参数的基本 R rep 函数

    > rep(Spread, times = NumberofTimes)
     [1] 0.06 0.06 0.06 0.06 0.17 0.14 0.14 0.07 0.07 0.07
    

    【讨论】:

      【解决方案2】:

      尝试使用mapply() 和带有rep() 的函数来包装SpreadNumberofTimes 之间的序列。代码如下:

      #Data
      NumberofTimes<-c(4,1,2,3)
      Spread<-c(0.060,0.170,0.140,0.070)
      #Apply
      vecval <- unlist(mapply(function(x,y) rep(x,y),x=Spread,y=NumberofTimes))
      

      输出:

      [1] 0.06 0.06 0.06 0.06 0.17 0.14 0.14 0.07 0.07 0.07
      

      【讨论】:

        【解决方案3】:

        Map 的选项

        unlist(Map(rep, Spread, NumberofTimes))
        

        【讨论】:

          猜你喜欢
          • 2016-09-19
          • 2019-02-23
          • 1970-01-01
          • 2017-04-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-30
          相关资源
          最近更新 更多