[R] If statement
Jeff Newmiller
jdnewm|| @end|ng |rom dcn@d@v|@@c@@u@
Fri Sep 13 02:01:47 CEST 2019
Use ifelse function, not if. If is only good for one logical value at a time, but you are working with long vectors of values simultaneously. I have no interest in doing all of your workfor you, but the concept is
cpl_or_sngl <- dat1$b %in% c( "couple", "single" )
a_pvt <- "private" == dat1$a
dat1$z <- with( dat1, ifelse( a_pvt & cpl_or_sngl, a, "Zero" ) )
dat1$y <- with( dat1, ifelse( a_pvt & cpl_or_sngl, c, 0 ) )
On September 12, 2019 4:06:59 PM PDT, 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?
>Thank you in advance
>
>______________________________________________
>R-help using 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.html
>and provide commented, minimal, self-contained, reproducible code.
--
Sent from my phone. Please excuse my brevity.
More information about the R-help
mailing list