[R] Subscripting problem with is.na()

ruipbarradas at sapo.pt ruipbarradas at sapo.pt
Thu Jun 23 16:24:58 CEST 2016


Hello,

You could do

ds_test[is.na(ds_test$var1), ] <- 0  # note the comma

or, more generally,

ds_test[] <- lapply(ds_test, function(x) {x[is.na(x)] <- 0; x})

Hope this helps,

Rui Barradas
 

Citando G.Maubach at weinwolf.de:

> Hi All,
>
> I would like to recode my NAs to 0. Using a single vector everything is
> fine.
>
> But if I use a data.frame things go wrong:
>
> -- cut --
>
> var1 <- c(1:3, NA, 5:7, NA, 9:10)
> var2 <- c(1:3, NA, 5:7, NA, 9:10)
> ds_test <-
> data.frame(var1, var2)
>
> test <- var1
> test[is.na(test)] <- 0
> test  # NA recoded OK
>
> # First try
> ds_test[is.na(ds_test$var1)] <- 0  # duplicate subscripts WRONG
>
> # Second try
> ds_test[is.na("var1")] <- 0
> ds_test$var1  # not recoded WRONG
>
> # Third try: to me the most intuitive approach
> is.na(ds_test["var1"]) <- 0  # attempt to select less than one element in
> integerOneIndex WRONG
>
> # Fourth try
> ds_test[is.na(var1)] <- 0  # duplicate subscripts for columns WRONG
>
> -- cut --
>
> How can I do it correctly?
>
> Where could I have found something about it?
>
> Kind regards
>
> Georg
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide  
> http://www.R-project.org/posting-guide.htmland provide commented,  
> minimal, self-contained, reproducible code.

 

	[[alternative HTML version deleted]]



More information about the R-help mailing list