Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in R Programming by (50.2k points)

I am having a data frame that is having a column named as the job with different categories like- Manager, Supervisor, SelfEmployed, Official, Highly professional employee, Low skilled worker, Unskilled worker. From that data frame, I would like to add a new column with a column name as the class where value 1 for high-class workers and 2 for low-class workers.

The data frame should look like:

head(df)

# Job                  Class

# Manager               1

# Supervisor            1

# Low skilled worker    2

# Low skilled worker    2 

# Unskilled worker      2

# Manager               1

1 Answer

0 votes
by (108k points)

You can either do that in the base R:

df$Class <- ifelse(df$Job %in% c("Manager", "Supervisor"), 1, 2)

or you can also use the dplyr package:

df <- df %>% 

  mutate(Class = ifelse(Job %in% c("Manager", "Supervisor"), 1, 2))

The data is:

df <- tribble(

  ~Job, ~Class,

  "Manager", 1,

  "Supervisor", 1,

  "Low skilled worker", 2, 

  "Low Skilled worker", 2,

  "Unskilled worker", 2, 

  "Manager", 1

)

If you are interested in R certification, then do check out the R programming certification

Related questions

Browse Categories

...