[R] need help in if else condition

Richard O'Keefe r@oknz @end|ng |rom gm@||@com
Wed Jul 10 12:19:35 CEST 2019


Since this has already been answered, I'll just mention one point that was
not addressed.
> d=c(1,2,3,"-","dnr","post",10)
This is rather odd.
> str(d)
 chr [1:7] "1" "2" "3" "-" "dnr" "post" "10"
You can create a vector of logical values, or a vector of numbers, or a
vector of strings,
but if there is a string there, logical values and numbers convert to
strings.
So why not write
> e <- c( 2 , 2 , 3 , 4 ,   5 ,    6 ,  7 )
> d <- c("1","2","3","-","dnr","post","10")
> m <- c("-" = 0, "dnr" = 0, "post" = 0)  # mask unwanted values
> de <- data.frame(d = d, e = e, f = ifelse(is.na(m[d]), d, "0"),
                   stringsAsFactors = FALSE)
> de
     d e  f
1    1 2  1
2    2 2  2
3    3 3  3
4    - 4  0
5  dnr 5  0
6 post 6  0
7   10 7 10

where the numbers in the d and f columns of the result are actually all
strings.


On Wed, 10 Jul 2019 at 19:54, Shubhasmita Sahani <
shubhasmita.sahani using gmail.com> wrote:

> Hello all,
> I am trying to run if else condition to alter my data. I have created a
> column F with reference to column d  where I want to replace the value to
> 0 where ever it finds a string or character value like  -,dnr, post and
> keep the rest of the rows should have the original value of column d. It is
> converting the text to 0 but the numeric values are not the same it is some
> value.. will you please help me to figure out why it is happening and what
> should be the proper code
>
> here are the code and the output
>
> d=c(1,2,3,"-","dnr","post",10)
> e= c(2,2,3,4,5,6,7)
> de<- as.data.frame(cbind(d,e))
> de$f<-ifelse (de$d=="-"|de$d=="dnr"|de$d=="post",0,de$d)
>
> head(de)
>
>   d e f
> 1  1 2 2
> 2  2 2  4
> 3  3 3 5
> 4  - 4 0
> 5  dnr 5 0
> 6 post 6 0
> why the values are changing in  with if else condition
>
>
> --
> Thanks & Regards,
> Shubhasmita Sahani
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>

	[[alternative HTML version deleted]]



More information about the R-help mailing list