Home > Software design >  ifelse statement for finding patterns and if true, code a value in another variable
ifelse statement for finding patterns and if true, code a value in another variable

Time:10-16

I have a dataframe with one column df$condition . It contains character strings, like "sunny", "sunshine", "dark", "night" and so on, 1 in each row. Now I want to code those in a second column df$code. If the value in df$condition in the row contains "sun", there should be a 1 in df$code, if it contains "dark" or "night" there should be a 2. Else if there is anything different or nothing, there should be a 99.

CodePudding user response:

As you have more than one condition, a case_when statement is most simple.

library(tidyverse)
data = data.frame(V1 = c("sunny", "sunshine", "dark", "night", "cloud"))

data %>%
    mutate(V2 = case_when(
        grepl("sun", V1) ~ 1,
        grepl("dark|night", V1) ~ 2,
        TRUE ~ 99
        )
    )
        V1 V2
1    sunny  1
2 sunshine  1
3     dark  2
4    night  2
5    cloud 99

CodePudding user response:

You can do this with a nested ifelse statement:

df$code <- with(df, ifelse(grepl("sun", condition), 1, ifelse(grepl("dark|night", condition), 2, 99)))

CodePudding user response:

Using dplyr

df <- data.frame(condition=c("sunny","sunshine","dark","night","somethingelse"))


df %>%
  mutate(code = if_else(grepl("sun",condition),1,
                        ifelse(condition=="dark"| condition=="night",2,99)))

Output:

      condition code
1         sunny    1
2      sunshine    1
3          dark    2
4         night    2
5 somethingelse   99
  •  Tags:  
  • r
  • Related