Add column with values depending on another column to a dataframe
You can nest ifelse
stataments. It's very handy when you are making categorical variables out of continuous ones.
data$c4 <- ifelse(data$c2 >= 0 & data$c2 <= 4, 'low',
ifelse(data$c2 >=5 & data$c2 <=9, 'medium',
ifelse(data$c2 >=10, 'High', 'something else')
df <- read.table(text = "
c1 c2 c3
x 2 z
y 5 f
c 3 r
a 11 z
", h = T)
df$c4 <- cut(df$c2, c(-Inf,4,9,Inf), c("low", "medium", "high"))
> df
c1 c2 c3 c4
1 x 2 z low
2 y 5 f medium
3 c 3 r low
4 a 11 z high