Error in group_by function in dplyr when used in Spotfire TERR
I have a table of patients where each patient (Unique Subject Identifier) has a nubmer of visits (Day 1, Day 2...Day 100) where their vital signs are collected. I would like create a new column where the value is their Respiratory rate (VSORRESN) minus their respiratory rate from Day 1. I need to do this for each patient so i've created the below data function in TERR. The code words flawlessly in R but i figured i'd run into some syntax issues in TERR. I'm getting the error below.
- Currently the group_by line is referencing the column name as a value "Unique Subject Identifer", is this the right way to tell it to group by each patient?
- Is the last line appropriate? I can't tell in Spotfire is understanding the brackets in the second term.
RESP <- VS %>% filter(VSTEST == "Respiratory Rate") %>% group_by("Unique Subject Identifier") %>% mutate(diff = (VSORRESN - VSORRESN[VISIT=="Day 1"]))
I see two problems with your code, although I cannot reproduce the exact error message with dplyr-0.7.4. Perhaps you used a different version of dplyr.
The argument to group_by() should be a name, not a character string. Names should be enclosed in "back quotes" (below the tilde on a PC keyboard), `Unique Patient Identifier`, if they include spaces or are otherwise not valid R names. You can backquote any name, but you must backquote non-syntactic names. If you supply a string, "Unique Patient Identifier", to group_by() , it puts the whole data.frame into one group. (To be more precise, group_by evaluates its arguments in an environment made from the columns of the data.frame passed in via "%>%".)
The other problem I see is that the code will misbehave if not all groups contain exactly one "Day 1" entry. (Because of the name vs. string issue above, you had only one group, hence will almost certainly run into this issue.) You change VSORRESN[VISIT=="Day 1"] to VSORRESN[VISIT=="Day 1"] so that it gives exactly one result, even if there are no Day 1 entries or more than one Day 1 entry. You could also add some code to warn if any group contained zero or more than one Day 1 entries.