Kyabdro
Kyabdro

Reputation: 75

Changing the position of a particular value in a vector

I'm sure someone have already ask the question in an other way somewere, but i'm not able to find it.

I want to change the position of a particular value in a vector. In the following example I put "eigth" in position 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"  

When the operation is carried out frequently, it becomes tiresome. I would like to do this in a very efficient and elegant way.

This response on a related post gave an usefull function to re-arrange columns order in a data-frame but not for vector in general. Something like this for a vector would be very good :

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

Is there any function that do this somewhere, or any idea to perform this very easily ?

Upvotes: 5

Views: 632

Answers (2)

DJJ
DJJ

Reputation: 2549

Building on GKI's solution.

   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"  

Caution: it is not robust to vector changes for instance

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

Would not work out of the box

Upvotes: 1

GKi
GKi

Reputation: 39727

You can use append to change the position of a particular value in a vector:

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

Upvotes: 5

Related Questions