how to create dummy variable using age group

21
my variable"age" looks like this, which is an age group.
but when I am trying to create age's dummy variable with the code

age1=ifelse(sr$age=="75+",1,0)

sr=data.frame(sr,age1)

and trying to add it to the dataset, the new variable "age1" doesn't show me "1" when age is "75+"
I think there may be some question in recognizing "age" as a categorical variable.
How should I deal with it?

Could you please turn this into a self-contained REPRoducible EXample (reprex)? Because I can't reproduce your issue, your code works as expected for me.

sr <- data.frame(stringsAsFactors = FALSE,
                 age = as.factor(c("75+", "55-74", "35-54", "25-34", "15-24", "5-14")),
                 value = 1:6)

age1 <- ifelse(sr$age=="75+",1,0)
sr <- data.frame(sr,age1)
sr
#>     age value age1
#> 1   75+     1    1
#> 2 55-74     2    0
#> 3 35-54     3    0
#> 4 25-34     4    0
#> 5 15-24     5    0
#> 6  5-14     6    0

Created on 2019-02-19 by the reprex package (v0.2.1)

Also, if you want to do one hot encoding you can use the caret package and encode all your variables at once

sr <- data.frame(stringsAsFactors = FALSE,
                 age = as.factor(c("75+", "55-74", "35-54", "25-34", "15-24", "5-14")),
                 value = 1:6)

library(caret)

dmy <- dummyVars(" ~ .", data = sr)
trsf <- data.frame(predict(dmy, newdata = sr))
trsf
#>   age.15.24 age.25.34 age.35.54 age.5.14 age.55.74 age.75. value
#> 1         0         0         0        0         0       1     1
#> 2         0         0         0        0         1       0     2
#> 3         0         0         1        0         0       0     3
#> 4         0         1         0        0         0       0     4
#> 5         1         0         0        0         0       0     5
#> 6         0         0         0        1         0       0     6
4 Likes

Thank you very very very much!
your idea about the package "caret" is really cool and useful!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.