hauger2
hauger2

Reputation: 35

Grouping factor variable

My factor variable -- var1-- has 7 levels to it, but I want to group levels 5-7 together.

I am thinking about doing something like

ifelse(var1 >= 5 ~ '5+', var1) 

but this logic is not working.

Upvotes: 0

Views: 148

Answers (2)

bft
bft

Reputation: 76

I am not sure of your desired output, but since you refer to a numeric 5 and wish to replace this with a character "5+" I would recommend something like the following using the mutate verb in dplyr:

library(dplyr)
data <- data.frame(response = seq(1,14), var1 = rep(1:7))
data <- data %>% mutate(var1 = factor(ifelse(var1 >= 5, "5+", var1)))
levels(data$var1)

Upvotes: 0

akrun
akrun

Reputation: 887118

The ifelse doesn't use ~, it would be , for yes and no arguments

ifelse(var1 >= 5, "5+", var1)

Upvotes: 1

Related Questions