# [R] If statement

Bert Gunter bgunter@4567 @end|ng |rom gm@||@com
Fri Sep 13 01:18:57 CEST 2019

```You appear to be confusing && with &  and || with |  ; (the first of each
pair take a logical expression, the second of each a logical vector) ...
as well as if ... else with ifelse (the first is a flow control statement
taking a logical expression; the second is a function taking a logical
vector as an argument).  I suggest you spend some time with an appropriate
R tutorial to clarify your understanding. You'll get a better explanation
and examples if you do so than anything I can provide you.

Incidentally, in future, do not tell us "it did not work." Provide the
specific error message that burped out.

Cheers,
Bert

Bert Gunter

"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )

On Thu, Sep 12, 2019 at 4:07 PM Val <valkremk using gmail.com> wrote:

> Hi all,
>
> I am trying to use the  if else statement and create  two new columns
> based on the existing two columns.  Below please find my sample data,
>
> dat1 <-read.table(text="ID  a b c d
> A private couple  25 35
> B private single  24 38
> C none  single    28 32
> E none none 20 36 ",header=TRUE,stringsAsFactors=F)
>
> dat1\$z <- "Zero"
> dat1\$y <-  0
>
> if a is "private" and (b is either "couple" rr "single"
>     then  z value = a's value   and y value = c's value
> if a is "none" and  ( b is either couple of single then  z= private
>   then  z value =b's value  qnd  y value= d's value
> else z value= Zero and y value=0
>
> the desired out put looks like
> ID          a      b      c     d     z       y
> 1  A private couple 25 35 private 25
> 2  B private single 24 38 private 24
> 3  C    none single 28 32 single  32
> 4  E    none   none 20 36 Zero    0
>
> my attempt
>
> if (dat1\$a =="private"  &  (dat1\$b =="couple"| dat1\$b =="single"))
> {
>       dat1\$z      <-   dat1\$a
>       dat1\$y      <-   dat1\$c
> }
>
> else if (dat1\$a =="none"  &  (dat1\$b =="couple"| dat1\$b =="single")) {
>     dat1\$z      <-   dat1\$b
>     dat1\$y      <-   dat1\$c
>   }
> else
> { default value}
> did not wok, how could I fix this?
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help