Re: [R] If Statement

From: Petr Savicky <savicky_at_praha1.ff.cuni.cz>
Date: Tue, 08 Mar 2011 16:29:00 +0100

On Tue, Mar 08, 2011 at 04:07:03AM -0800, dpender wrote:
> Hi,
>
> I am having some problems using the if statement correctly. I have used it
> many times previously so I dona't know what is different with this case.
> Here is my problem:
>
> I have a 1X10 matrix of values as follows:
>
> > H.MC
> [,1]
> [1,] 4.257669
> [2,] 7.023242
> [3,] 4.949857
> [4,] 5.107000
> [5,] 4.257669
> [6,] 4.257669
> [7,] 4.257669
> [8,] 4.257669
> [9,] 4.257669
> [10,] 4.257669
>
> What I want to do is replace all the values if 4.257669 with a random number
> between 3 and 4.5. To do this I have:
>
> H.MC.fin <- matrix(0,10,1)
>
> for (j in 1:10) {
>
> if(H.MC[j] == 4.257669) H.MC.fin[j] <-runif(1,3,4.5) else H.MC.fin[j] <-
> H.MC[j]
>
> }
>
> This doesn't seem to do anything and H.MC.fin is the same as H.MC.

Hi.

It is likely that none of the numbers in H.MC is exactly 4.257669. This is easy to check by printing

  H.MC - 4.257669

The condition H.MC[j] == 4.257669 is satisfied for those numbers, which are printed as 0. If there are numbers close to 4.257669, but not exactly equal, try to determine the maximum difference from 4.257669, which should still be interpreted as equality.

The function all.equal(), which is suggested for comparison of numeric values, reports the numbers as equal, if their relative difference is at most (approx) 1.5e-8. Use it, for example, as

  isTRUE(all.equal(H.MC[j], 4.257669))

If an absolute error is more suitable, try using

  abs(H.MC[j] - 4.257669) < 1e-10

with a possibly different bound.

Hope this helps.

Petr Savicky.



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. Received on Tue 08 Mar 2011 - 15:33:01 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 08 Mar 2011 - 15:50:19 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive