pat28dh
pat28dh

Reputation: 87

With ifelse can I create range and have a blank output if if it's false so I can create another ifelse

I have coordinate in 2 different vectors named x and y. I want to create a third variable telling in which cadran (quarter) they are. With my ifelse statement I cannot figure out to use a range as an example x would be 25>x>0 and 25>y>0 instead of just being x>0 & y>0 . Also because I want to create this variable with multiple cadran I would like to have multiple ifelse statement that does not erase each others. so at the end my third column gives me the cadran for each of these pair of x and y

Here is my code so far and I am kind of block here

library(dplyr)

x <- c(3,-2, 35, -4, 34, 20, 45)
y <- c(0, 2, 33, -4, 50, 30, 10)

df <- cbind.data.frame(x, y)
df

#Creating  a third variable reacting to coordinate
df$quart <-ifelse(df$x>0 & df$y>0, "quart1", NA)
df$quart <-ifelse(df$x<0 & df$y<0, "quart2", NA)
df

Thank you for your help

Upvotes: 1

Views: 521

Answers (2)

Simple approach

You can use multiple ifelse() in the same conjunction, it may seem difficult to overview in the beginning, but using indentation styles which makes sense to you, could get you some of the way.

#Creating  a third variable reacting to coordinate

df$quart <- ifelse(
  df$x<0 & df$y<0,
  "quart3",
  ifelse(
    df$x<25 & df$y<25,
    "quart2",
    ifelse(
      df$x<50 & df$y<50,
      "quart1",
      "other"
    )
  )  
)

Note that with this approach, quart = "other" if X and Y are equal to 0, or 25, or 50, or >50. Consider the use of <= instead of <.

Improved readability

I suggest that you utilize dplyr, for easier readability.

library(dplyr)

df <- data.frame(
  x = c(3,-2, 35, -4, 34, 20, 45),
  y = c(0, 2, 33, -4, 50, 30, 10)
)

df <- mutate(
  df,
  quart = ifelse(
    x < 0 & y < 0,
    "quart3",
    ifelse(
      x < 25 & y < 25,
      "quart2",
      ifelse(
        x < 50 & y < 50,
        "quart1",
        "other"
      )
    )  
  )
)

The strength in using mutate is that it is really easy to navigate you variables (columns), as each row is handled independently, instead of handling the entire x and y vectors. This makes a difference, if you need to use functions which doesn't handle vectors with more than a single value.

After reading OP comment and OP answer, I updated the answer.

Upvotes: 1

pat28dh
pat28dh

Reputation: 87

Using case_when ended up being the easiest way of doing for me. Thank you for your comments/solutions

df <- data.frame(
  x = c(3,-2, 35, -4, 34, 20, 45),
  y = c(0, 2, 33, -4, 50, 30, 10)
)

df

df %>% 
  mutate(category = case_when(
    x > 25 & y >25   ~ "q1",
    x > 0 & y > 0   ~ "q2",
    x < 0 & y < 0 ~ "q3", 
    TRUE ~ "other"
  )
  )

Upvotes: 0

Related Questions