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

Sarah Goslee sarah.goslee at gmail.com
Thu Sep 18 20:08:16 CEST 2014


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)


> d
  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!
>
> 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?
>
> 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



-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list