Creating a new variable based on condition

Hi,
I have a dataset with school names and teachers as in the dataframe "data". I need to create a new variable by which the first teacher of the first school is called "Class 1" and second teacher is called "Class 2". This system then proceeds for all schools as shown in the dataframe "data1".
How can I do this?

library(tidyverse)


data<-tibble::tribble(
            ~school_name, ~teacher_name,
            "GHPS UNKAL",      "Nithin",
            "GHPS UNKAL",      "Naveen",
         "GHPS BYAHATTI",       "Bindu",
         "GHPS SHIVALLI",       "Julia",
        "GHPS REVADIHAL",       "Nutan",
        "GHPS REVADIHAL",       "Zidan"
        )

data1<-tibble::tribble(
             ~school_name, ~teacher_name, ~class_number,
             "GHPS UNKAL",      "Nithin",     "Class 1",
             "GHPS UNKAL",      "Naveen",     "Class 2",
          "GHPS BYAHATTI",       "Bindu",     "Class 1",
          "GHPS SHIVALLI",       "Julia",     "Class 1",
         "GHPS REVADIHAL",       "Nutan",     "Class 1",
         "GHPS REVADIHAL",       "Zidan",     "Class 2"
         )
Created on 2022-07-22 by the reprex package (v2.0.1)

Here is one method.

data<-tibble::tribble(
   ~school_name, ~teacher_name,
   "GHPS UNKAL",      "Nithin",
   "GHPS UNKAL",      "Naveen",
   "GHPS BYAHATTI",       "Bindu",
   "GHPS SHIVALLI",       "Julia",
   "GHPS REVADIHAL",       "Nutan",
   "GHPS REVADIHAL",       "Zidan"
 )
data |> group_by(school_name) |>  
   mutate(Class_number = paste("Class", row_number()))
# A tibble: 6 x 3
# Groups:   school_name [4]
  school_name    teacher_name Class_number
  <chr>          <chr>        <chr>       
1 GHPS UNKAL     Nithin       Class 1     
2 GHPS UNKAL     Naveen       Class 2     
3 GHPS BYAHATTI  Bindu        Class 1     
4 GHPS SHIVALLI  Julia        Class 1     
5 GHPS REVADIHAL Nutan        Class 1     
6 GHPS REVADIHAL Zidan        Class 2     
2 Likes

I'm just here to advocate for data.table.

data[, Class := paste("Class", 1:.N), school_name]
      school_name teacher_name   Class
1:     GHPS UNKAL       Nithin Class 1
2:     GHPS UNKAL       Naveen Class 2
3:  GHPS BYAHATTI        Bindu Class 1
4:  GHPS SHIVALLI        Julia Class 1
5: GHPS REVADIHAL        Nutan Class 1
6: GHPS REVADIHAL        Zidan Class 2
1 Like

Thank you for the answer..

Regards,
Nithin

Thank you very much for this..

Regards,
Nithin

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.