[R] Neat conditional assignment

markleeds at verizon.net markleeds at verizon.net
Tue Dec 11 00:51:31 CET 2007

>From: Neil Stewart <neil.stewart at warwick.ac.uk>
>Date: 2007/12/10 Mon PM 05:41:34 CST
>To: r-help at stat.math.ethz.ch
>Subject: [R] Neat conditional assignment

d <- ifelse(a == "A",b,c)

>I would like to make a new vector with values taken from two existing
>vectors conditional upon a third. At present I am doing this with a for loop
>but wonder if there is not a neater way, given some of the very neat things
>R can do.
>a is thus "A" "B" "A" "B" "A" "B"...
>b is thus 1 1 1 1 1 1 ...
>c is thus 2 2 2 2 2 2 ...
>I want d[i] to be b[i] if a[i]=="A" and c[i] if a[i]=="B". I'm current using
>a for loop:
>d<-rep(0,100)     # initialise d
>for(i in 1:length(a)) {if(a[i]=="A") d[i]<-b[i] else d[i]<-c[i]}
>d is thus 1 2 1 2 1 2 1 2 1 ...
>Is it possible to do something simpler, say along the lines of the c-style
>?: conditional statement, or at least avoiding the for loop.
>d <- a=="A"?b:c   # doesn't work, but you get the idea
>Thanks in advance,
>R-help at r-project.org mailing list
>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