[R] ifelse(is.na), with function inside

Gabor Grothendieck ggrothendieck at gmail.com
Wed Jun 17 06:19:52 CEST 2009


Try:

2 - is.na(a)


On Tue, Jun 16, 2009 at 5:46 PM, Grześ<gregorio99 at gmail.com> wrote:
>
> Hi,
> I have a vector a=c(NA, 3, 4, 4, NA, NA, 3) and I would like to use is.na(a)
> function to get a vector like this:
> wy=(1,2,2,2,1,1,2) - you know, this vector create 1 or 2 depends on value in
> vector "a"
>
> This is my short code but something is wrong and I don't know what...
>
> for (i in 1:7){
>  a=c( NA, 3, 4, 4, NA, NA, 3)
>  fun1=function(x){
>  x=1
>  print(x)
>  }
>  fun2=function(x){
>  x=2
>  print(x)
>  }
>  wy[i]<- ifelse(((is.na(a))), fun1(x), fun2(x))
>  }
> [1] 1
> [1] 2
> [1] 1
> [1] 2
> [1] 1
> [1] 2
> [1] 1
> [1] 2
> [1] 1
> [1] 2
> [1] 1
> [1] 2
> [1] 1
> [1] 2
> and I get a lots of warnings:
> Warning messages:
> 1: In wy[i] <- ifelse(((is.na(a))), fun1(x), fun2(x)) :
>  number of items to replace is not a multiple of replacement length
> 2: In wy[i] <- ifelse(((is.na(a))), fun1(x), fun2(x)) :
>  number of items to replace is not a multiple of replacement length...
>
> and as an result I get a vector only with 1
>> wy
> [1] 1 1 1 1 1 1 1
>
> I'll be very happy if someone help me
>
> --
> View this message in context: http://www.nabble.com/ifelse%28is.na%29%2C-with-function-inside-tp24063455p24063455.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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