Replacing all instances of -99 to NA

#1
Deal all,

I wrote this user defined function. It should get a dataframe ds and a number x, and replace all instances of x to missing values.

When I ran the loop without defining a function, it worked. But after I put this code in a function, it does nothing...

What is wrong with my code, why isn't it working ?

Thank you in advance !

Code:
repMissing = function(ds,x)
{
  for(i in 1:nrow(ds))
  {
    for(j in 1:ncol(ds))
    {
      if (!is.na(ds[i,j]) && ds[i,j] == x)
      {
        ds[i,j] = NA
      }
    }
  }
}
Code:
repMissing(diet2,-99)
 

Dason

Ambassador to the humans
#2
You need to return ds at the end
Code:
repMissing = function(ds,x)
{
    for(i in 1:nrow(ds))
    {
        for(j in 1:ncol(ds))
        {
            if (!is.na(ds[i,j]) && ds[i,j] == x)
            {
                ds[i,j] = NA
            }
        }
    }
    return(ds)
}
The last 'statement' in your function is a for loop and for loops return NULL as their result so that's what is getting returned from the function unless you specify to return the modified ds. But with that said...

Code:
ds[ds == x] <- NA
works just fine. No need for looping.