Sarang - 3 months ago 27

R Question

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 ?

Answer

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)
```