Sarang Manjrekar
Sarang Manjrekar

Reputation: 1991

inplace Modifying a vector in R

I have a vector 'participant' in R.

> participant
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

I am using a function 'modify' to change the contents of this vector.

modify <- function(x){
    for (i in participant){ 
    if (x[i] > 12) 
        (x[i]=x[i]-12)
        print (x[i])
}}

When I run the function as modify(participant), it runs OK, but the elements of the vector participant remain unchanged.

Any suggestion, for where am I going wrong ?

Upvotes: 0

Views: 208

Answers (2)

J_F
J_F

Reputation: 10352

Your problem is the function return. Use this solution, so the function returns the modified vector x:

modify <- function(x){
  for (i in participant){ 
    if (x[i] > 12) 
      (x[i] = x[i] - 12)
      print (x[i])}
  return(x)
  }

participant  <- modify(participant)

Another solution is the ifelse function:

participant <- ifelse(participant > 12, participant - 12, participant)

Upvotes: 1

Roland
Roland

Reputation: 132576

Don't use a loop.

participant <- participant - (participant > 12) * 12 

If you insist on using your function, loop over the indices, let you function return the modified vector and assign it:

modify <- function(x){
    for (i in seq_along(participant)){ 
      if (x[i] > 12) x[i]=x[i]-12
    } 
  return(x)
}

participant <- modify(participant)

Of course, the loop is more difficult to write and also much slower.

Upvotes: 5

Related Questions