George -
   I think you're looking for the ifelse function:

X = c(100,125,110,90)
Y = c(200,110,150,200)
Z = c(125,105,130,75)
AA = c(150,140,200,65)
result = ifelse(X < Z & Y > Z,AA - Z,NA)
result
[1] 25 NA 70 NA
result[!is.na(result)]
[1] 25 70

(I'm assuming you said 50 when you meant 70.)

                                        - Phil Spector
                                         Statistical Computing Facility
                                         Department of Statistics
                                         UC Berkeley
                                         spec...@stat.berkeley.edu

On Thu, 16 Sep 2010, George Coyle wrote:

Hello,

I wrote this code which works fine on a single observation:

x<-100
y<-200
z<-125
aa<-150
if(x<z && y>z) {aa-z}
result: 25

I am trying to apply this logic where x,y,z,and aa are arrays but with very
little success.  I have tried using loops and whiles but I always get errors
of various types.  I have consulted a few manuals but with limited success.
My hopeful outcome would be:

data:
   X       Y      Z      AA
1 100  200    125     150
2 125   110    105    140
3 110    150   130    200
4 90    200     75    65

Here row 1 would return 25, row 2 would return nothing since Z<X, row 3
would be 50, row 4 would be nothing since X>Z.

In this case I am trying to return something where I could call the output a
variable "Z" which would become an array based on the logic above where the
members would be: (25, 50)

I tried using this where the variables are arrays:
if(x<z && y>z) {aa-z}
But I get "NULL"

I tried using this where the variables are arrays:
if(x<z && y>z) {aa-z} else "NA"
But I get "NA"

When I tried using a loop:
for(i in 1:length(x)) if(x<z && y>z) {aa-z} else "NA"
I got "NULL"

An attempt at a "while" statement crashed.

The time series resource (
http://cran.r-project.org/doc/contrib/Ricci-refcard-ts.pdf) is way too
involved.  Most online sources I am finding are not good for "if" contingent
array manipulation.  Annoyingly, just saying aa-z will work across the
entire array but for some reason my ifs fail.  I know the R help group only
wants serious emails so hopefully this will indicate I gave it a
reasonable shot.

Please help

Thanks

        [[alternative HTML version deleted]]

______________________________________________
R-help@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.


______________________________________________
R-help@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.

Reply via email to