else if statement to create a new column

Viewed 37

I have a data frame of multiple columns. I want to create a new colomn called second.indicator with the following :

second.indicator == -1 if il.count.description + un.count.description > elle.count.description + une.count.description

second.indicator == 0 if il.count.description + un.count.description) == elle.count.description + une.count.description

else second.indicator == 1

the output is many error messages : 'second.indicator' not found / Error: unexpected '}' in " }"

il.count.descrition elle.count.description un.count.description un.count.description
     5                      1                      5                    1
     9                      2                      2                    6
     1                      1                      0                    0
     10                     9                      0                    8

data <- data %>% 
  mutate(second.indicator =
           if (il.count.description + un.count.description) > elle.count.description + une.count.description) {
    second.indicator == -1
    } else if (il.count.description + un.count.description) == (elle.count.description + une.count.description) {
      second.indicator == 0
      } else {
        second.indicator == 1
        }
2 Answers

You cannot use if-statements inside mutate like that (for multiple reasons); instead you could use case_when:

data <-
  data %>% 
  mutate(second.indicator = case_when((il.count.description + un.count.description) > (elle.count.description + une.count.description) ~ -1,
                                      (il.count.description + un.count.description) == (elle.count.description + une.count.description) ~ 0,
                                      T ~ 1
                                      )

df being your data ...

df <- structure(list(il = c(5L, 9L, 1L, 10L), elle = c(1L, 2L, 1L, 9L), un = c(5L, 2L, 0L, 0L), une = c(1L, 6L, 0L, 8L)), class = "data.frame", row.names = c(NA, 4L))

(redundant ".count.description" omitted from variable names)

... you can avoid the typo-prone if-else-hazzle like so:

df %>%
  mutate(second_indicator = sign((elle + une) - (il + un)))

Related