Home > front end >  Create a new column when respondents have the same ID but different type of variables in R
Create a new column when respondents have the same ID but different type of variables in R

Time:12-14

I am interested in identifying the respondents (i.e. nurses) in my dataset based on their contracts. Some nurses have the same ID number but different types of contracts. For such nurses, I want to create a new column "nurse type" based on the information in the column "Contract" to know when nurses work substantive and bank shifts.

For instance, if a nurse (with the same ID) has 2 contracts, i.e. NHSp Bank contract & Agenda for Change, then I need to add "Substantive with Bank" in the new column.

Here is an example of the dataset I currently have:

|ID number|Contract|
|:-------:|:------:|
|S12151617|NHSp Bank contract|Substantive with bank
|S12151617|Agenda for change|Substantive with bank

Here is the dataset that I need to distinguish the different type of nurses based on their contract (column "nurse type")

|ID number|Contract|Nurse type|
|:-------:|:------:|:---------:|
|S12151617|NHSp Bank contract|Substantive with bank
|S12151617|Agenda for change|Substantive with bank

Any help on the coding would be greatly appreciated. Thanks

CodePudding user response:

I do not think I fully understand your question, but I have the feeling that what you need are functionalities to work with string data. In that case, check the stringr library. Probably something like:

library(tidyverse)
library(stringr)

Data <- data.frame(
  IdNumber = c("S12151617", "S12151617"),
  Contract = c("NHSp Bank contract|Substantive with bank",
               "Agenda for change|Substantive with bank"))

Data$NurseType <- str_detect(Data$Contract, "Substantive with bank")
Data$NurseType <- ifelse(Data$NurseType, "Substantive with bank", "Other")

CodePudding user response:

Data$NurseType = ifelse(Data$Contract == "SOME CRITERIA", "Substantive with bank", "Other")

or by subsetting

Data$NurseType[Data$Contract == "SOME CRITERIA",] = "Substantive with bank"
  • Related