Skip to content

"missings=function(x) x[x==998|x==999]<-NA" doesn't work...

3 messages · Doreen Mueller, Sarah Goslee, Ben Tupper

#
Hi!

I want to have a function that assigns NAs to certain values of my 
variable "var" in the dataset "d". This doesn't work:
0      1  999 <NA> 
 220  752  321 5264 

I don't get any error messages, but "d$var" remains unchanged. The 
function:
doesn't work either, and I read that "<<-" is "dangerous" anyway?

It is important for me to work with variable names (and therefore with 
functions instead loops) because the number and order of variables in my 
dataset changes regularly.

Thank you,
Doreen
#
You need to assign the output of missings() to something. For that
matter, missings() needs some output.

d <- data.frame(a=1:5, b=6:10, var=c(1, 1, 998, 999, 2))

missings <- function(x) {
    x[x==998|x==999]<-NA
    x
}

d$var <- missings(d$var)
a  b var
1 1  6   1
2 2  7   1
3 3  8  NA
4 4  9  NA
5 5 10   2


Sarah
On Thu, Sep 18, 2014 at 10:13 AM, Doreen Mueller <Doreen.Mueller at dza.de> wrote:

  
    
#
Hi,
On Sep 18, 2014, at 10:13 AM, Doreen Mueller <Doreen.Mueller at dza.de> wrote:

            
You are so close.  R returns the value of the last thing evaluated in your function.  In this case, the *copy* of your input argument was modified within the function, but you didn't return the value of the copy to the calling environment.  You need to explicitly return the modified value.
[1]  990  991  992  993  994  995  996  997   NA   NA 1000 1001 1002 1003 1004 1005 1006 1007
[19] 1008 1009 1010

By the way, don't forget to switch your email client to use text instead of html when sending a message to the list.

Cheers,
Ben