[R] "missings=function(x) x[x==998|x==999]<-NA" doesn't work...
Ben Tupper
ben.bighair at gmail.com
Thu Sep 18 20:15:25 CEST 2014
Hi,
On Sep 18, 2014, at 10:13 AM, Doreen Mueller <Doreen.Mueller at dza.de> wrote:
> 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:
>
>> missings=function(x) x[x==998|x==999]<-NA
>> missings(d$var)
>> table(d$var, useNA="always")
>
> 0 1 999 <NA>
> 220 752 321 5264
>
> I don't get any error messages, but "d$var" remains unchanged. The
> function:
>> missings=function(x) x[x==90|x==99]<<-NA
> doesn't work either, and I read that "<<-" is "dangerous" anyway?
>
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.
> missings <- function(x) { x[ (x==998) | (x==999) ] <- NA ; return(x) }
> missings(990:1010)
[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
> 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
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list