Home > Blockchain >  Why isn't the mutate function creating the new column?
Why isn't the mutate function creating the new column?

Time:03-10

r beginner here.

I'm trying to create a new column with the following code:

data %>% mutate(age_cat = if_else(suspect_age %in% 0:14, "Under 15", if_else(suspect_age %in% 15:24, "15-24", ifelse(suspect_age %in% 25:34, "25-34", ifelse(suspect_age %in% 35:44, "35-44", ifelse(suspect_age %in% 45:54, "45-54", ifelse(suspect_age %in% 55:64, "55-64", "65 & over")))))))

But the new column isn't actually being created, why is that?

Thank you in advance!

CodePudding user response:

With tidyverse, you can use case_when instead of all the ifelse statements. If on the left of ~ is TRUE, then execute what is on the right of ~. With the new column, you just need to assign it to a variable. Or if you just need to quickly view the dataframe, then you can add on %>% view.

library(tidyverse)

results <- data %>% 
  mutate(age_cat = case_when(suspect_age %in% 0:14 ~ "Under 15",
                                    suspect_age %in% 15:24 ~ "15-24",
                                    suspect_age %in% 25:34 ~ "25-34",
                                    suspect_age %in% 35:44 ~ "35-44",
                                    suspect_age %in% 45:54 ~ "45-54",
                                    suspect_age %in% 55:64 ~ "55-64",
                                    TRUE ~ "65 & over"))

Output

results

   suspect_age   age_cat
1           12  Under 15
2           77 65 & over
3           21     15-24
4           36     35-44
5           58     55-64
6           11  Under 15
7           74 65 & over
8           92 65 & over
9           32     25-34
10          31     25-34

Or another option is to use cut:

data %>%
  mutate(age_cat = cut(suspect_age, breaks = c(0, seq(14, 64, 10), 110),
                       labels = c("Under 15", "15-24", "25-34", "35-44", "45-54", "55-64", "65 & over"),
                       include.lowest = TRUE))

Data

data <- structure(list(suspect_age = c(12L, 77L, 21L, 36L, 58L, 11L, 
74L, 92L, 32L, 31L)), class = "data.frame", row.names = c(NA, 
-10L))

CodePudding user response:

I'm presuming you are expecting the new column to be present in data after you run that command.

In that case, you need to assign it.

data <- data %>% mutate(age_cat = if_else(suspect_age %in% 0:14, "Under 15", if_else(suspect_age %in% 15:24, "15-24", ifelse(suspect_age %in% 25:34, "25-34", ifelse(suspect_age %in% 35:44, "35-44", ifelse(suspect_age %in% 45:54, "45-54", ifelse(suspect_age %in% 55:64, "55-64", "65 & over")))))))

  • Related