[R] For loop with i and j and multiple if statements... help!
Sarah Goslee
sarah.goslee at gmail.com
Thu Oct 18 17:52:07 CEST 2012
There are a bunch of things wrong with your code, from not
understanding subsetting to only returning a single value rather than
a vector of values. I highly recommend that you read the Introduction
to R document that came with your R installation and is readily
available online.
In the meantime:
testdata <- structure(list(x = c(701L, 685L, 566L, 562L, 601L, 608L),
y = c(209L,
209L, 248L, 234L, 225L, 232L)), .Names = c("x", "y"), class =
"data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))
lookzone <- with(testdata, ifelse(x > 170 & x < 1250 & y > 150 & y <
480, 1, ifelse(x > 170 & x < 420 & y > 480 & y < 810, 2, NA)))
> lookzone
[1] 1 1 1 1 1 1
Or, with sample data that includes all the combinations:
> testdata <- data.frame(x = c(701, 685, 100, 100, 1300, 400, 400), y=c(209, 209, 100, 300, 300, 500, 100))> lookzone <- with(testdata, ifelse(x > 170 & x < 1250 & y > 150 & y < 480, 1, ifelse(x > 170 & x < 420 & y > 480 & y < 810, 2, NA)))
> lookzone
[1] 1 1 NA NA NA 2 NA
Sarah
On Thu, Oct 18, 2012 at 10:51 AM, ingaschwabe <ingaschwabe at gmail.com> wrote:
> Dear all,
>
> Thanks for the many replies!
>
> Indeed, the function does not represent my explanation. It should have been:
>
> if (x[i] > 170 && x[i] < 1250 && y[j] > 150 && y[j] < 480)
>
> Sorry, my mistake.
>
> My data looks like this:
> head(input[,3:4])
> x y
> 1 701 209
> 2 685 209
> 3 566 248
> 4 562 234
> 5 601 225
> 6 608 232
>
>
> Refering to the last post, I guess that my function then should look like
> something like this:
>
> test <- apply(input,1,function(x){
> lookzone<-NULL
> if (x[1] > 170 && x[1] < 1250 && y[1] > 150 && y[1] < 480)
> {lookzone<-1}
> if (x[1] > 170 && x[1] < 420 && y[1] > 480 && y[1] < 810)
> {lookzone <- 2}
> return(lookzone)
> })
>
> however, when I run the function then nothing happens.
>
> and when I ask explicitly for the result then I get this
>> test
> NULL
>
> Can someone tell me what goes wrong here? Or give a hint?
> I'm not used to using the apply function and do use the for loop on the
> basis of an example that I once made so I am not a very experienced R user..
>
> Thank you so much for your help!
> I really appreciate it!
>
> Bye,inga
>
>
>
--
http://www.functionaldiversity.org
More information about the R-help
mailing list