1

I have a dataframe that looks like this:

names <- c("Lucy", "Sally", "Harry", "Betsy")
values <- c(1, 2, 3, 4)
df <- data.frame(names, values)

I want to make another column that has a value of Low if the value is 1 or 2, and High if the value is 3 or 4. I can do it like this in base R

df$var[df$values == 1 | df$values == 2] = "Low"
df$var[df$values == 3 | df$values == 4] = "High"

But how do I do it in tidyverse? I've tried using pipes and filter but that hasn't worked so far.

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
eclare
  • 139
  • 5

2 Answers2

4
df %>%
  mutate(category = ifelse(values < 3, "Low", "High"))
 
Teddly
  • 110
  • 6
1

You can also use the following solution:

library(dplyr)


df %>%
  mutate(var = case_when(
    values %in% c(1, 2) ~ "Low", 
    values %in% c(3, 4) ~ "High",
    TRUE ~ as.character(values)
  ))


  names values  var
1  Lucy      1  Low
2 Sally      2  Low
3 Harry      3 High
4 Betsy      4 High

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41