0

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 ?

1
  • 1
    I would go with participant[participant > 12] <- participant[participant > 12] - 12 Commented Nov 15, 2016 at 8:31

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.