【问题标题】:Changing the position of a particular value in a vector更改向量中特定值的位置
【发布时间】:2020-07-07 09:10:53
【问题描述】:

我确定有人已经以其他方式提出了这个问题,但我找不到。

我想改变向量中特定值的位置。在以下示例中,我将“eigth”放在第 4 位。

vector<-c("one","two","three","four","five","six","seven","eight","nine","ten")
vector
# [1] "one"   "two"   "three" "four"  "five"  "six"   "seven" "eight" "nine"  "ten" 

vector<-vector[c(1:3,8,4:7,9:10)]
vector
# [1] "one"   "two"   "three" "eight" "four"  "five"  "six"   "seven" "nine"  "ten"  

当频繁进行操作时,它变得令人厌烦。我想以一种非常有效和优雅的方式做到这一点。

This response on a related post 提供了一个有用的函数来重新排列数据框中的列顺序,但通常不适用于向量。像这样的向量会非常好:

arrange.vect(vector, c("eigth"=4))
# [1] "one"   "two"   "three" "eight" "four"  "five"  "six"   "seven" "nine"  "ten"  

是否有任何功能可以在某处执行此操作,或者有什么想法可以很容易地执行此操作?

【问题讨论】:

    标签: r vector


    【解决方案1】:

    您可以使用append 更改向量中特定值的位置

    append(vector[-8], vector[8], 3)
    # [1] "one"   "two"   "three" "eight" "four"  "five"  "six"   "seven" "nine"  "ten"  
    

    【讨论】:

      【解决方案2】:

      以 GKI 的解决方案为基础。

         arrange.vect <- function(vect,what,where) { 
           ### purpose 
           ## change the position of what in vect to where  
           ### DD 
           ## vect . vector
           ## what  . element of vector 
           ## where . new position of what 
            idx <- which(vect==what); 
            append(vector[-idx], vector[idx], where-1)
          }
      
      
      > arrange.vect(vector,"eight", 4)       
      ##  [1] "one"   "two"   "three" "eight" "four"  "five"  "six"   "seven" "nine"  "ten"  
      

      注意:例如,它对向量变化并不鲁棒

      arrange.vect(vector,c("eight","one"), c(4,8))
      

      不能开箱即用

      【讨论】:

        猜你喜欢
        • 2017-12-05
        • 1970-01-01
        • 1970-01-01
        • 2017-09-10
        • 1970-01-01
        • 2017-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多