lundi 1 février 2021

R - ifelse statement with two conditions

I'm new to R and want to understand why "ifelse" fails in my case.

I have a vector of longitudes and radii. If the lons are < 0 then the code should do lons - (zrad/dxy), if lons are >= 0 then lons + (zrad/dxy) should be calculated.

Some example data:

lons <- c(-80,4)
zrad <- c(747,576)
dxy  <- 222
test <- ifelse(lons < 0 | lons >= 0, lons - (zrad/dxy), lons + (zrad/dxy))
View(test)

This gives me

1   -83.364865
2   1.405405

However, lons - (zrad/dxy) is

-83.364865  1.405405 

and lons + (zrad/dxy) is

-76.635135  6.594595

But the right result should be

-83.364865 6.594595

Do I need to use a for-loop so that "test" includes the result from the first and second calculation? Or is there an easier way to differentiate the two cases(conditions)?

Aucun commentaire:

Enregistrer un commentaire