Kate Ignatius
2014-Oct-01 22:11 UTC
[R] How to check to see if a variable is within a range of another variable
Is there an easy way to check whether a variable is within +/- 10% range of another variable in R? Say, if I have a variable 'A', whether its in +/- 10% range of variable 'B' and if so, create another variable 'C' to say whether it is or not? Is there a function that is able to do that? eventual outcome: A B C 67 76 no 24 23 yes 40 45 yes 10 12 yes 70 72 yes 101 90 no 9 12 no
Peter Langfelder
2014-Oct-01 22:29 UTC
[R] How to check to see if a variable is within a range of another variable
On Wed, Oct 1, 2014 at 3:11 PM, Kate Ignatius <kate.ignatius at gmail.com> wrote:> Is there an easy way to check whether a variable is within +/- 10% > range of another variable in R?Yes, checkRange = function(A, B, range = 0.1) { A>=B*(1-range) & A<=B*(1+range); } Test: A = c(67, 24, 40, 10, 70, 101, 9) B = c(76, 23, 45, 12, 72, 90, 12) outcome = checkRange(A, B) You can create the desired data frame for example as data.frame (A = A, B=B, C = c("no", "yes")[outcome+1])> > Say, if I have a variable 'A', whether its in +/- 10% range of > variable 'B' and if so, create another variable 'C' to say whether it > is or not?What do you mean by range of variable B? In your example below, 40 is not within 10% of 45, which is 4.5; 10 is not within 10% of 12 which is 1.2.> > eventual outcome: > A B C > 67 76 no > 24 23 yes > 40 45 yes > 10 12 yes > 70 72 yes > 101 90 no > 9 12 noHTH, Peter
Peter Alspach
2014-Oct-01 22:54 UTC
[R] How to check to see if a variable is within a range of another variable
Tena koe Kate If kateDF is a data.frame with your data, then apply(kateDF, 1, function(x) isTRUE(all.equal(x[2], x[1], check.attributes = FALSE, tolerance=0.1))) comes close to (what I think) you want (but not to what you have illustrated in your 'eventual outcome'). Anyhow, it may be enough to allow you to get there. HTH .... Peter Alspach -----Original Message----- From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Kate Ignatius Sent: Thursday, 2 October 2014 11:11 a.m. To: r-help Subject: [R] How to check to see if a variable is within a range of another variable Is there an easy way to check whether a variable is within +/- 10% range of another variable in R? Say, if I have a variable 'A', whether its in +/- 10% range of variable 'B' and if so, create another variable 'C' to say whether it is or not? Is there a function that is able to do that? eventual outcome: A B C 67 76 no 24 23 yes 40 45 yes 10 12 yes 70 72 yes 101 90 no 9 12 no ______________________________________________ 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. The contents of this e-mail are confidential and may be ...{{dropped:14}}