I have long form data which I am not able to turn into short form yet (it is too large and complicated at this stage). My data contains information on hospital episodes, with each line corresponding to a new episode.
I am trying to create a new variable from another variable, but I can’t get the group_by function to work.
I am trying to make a new binary variable that tells me if an individual has ever been hospitalised with a cardiac arrest (Y/N) using a variable that tells me the reason for each hospitalisation episode.
As I have multiple entries per person I assume I need to group by ‘ID’ to get the same binary outcome for each entry for each person.
This is my code:
data %>%
group_by(ID) %>%
mutate(Ever_Cardiac =
ifelse(reason_for_hospitalisation == “Cardiac”, ‘1’, ‘0’)
The second bit of the code is working, in that an “Ever_Cardiac” column is created, with ‘1’s for “Cardiac” and ‘0’ for any other categories.
However, for individuals with multiple hospital episodes, I only get a ‘1’ for episodes that were due to a cardiac arrest not for their other episodes.
Can anyone help me?
user25184725 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.