-2

I have a homework question: "For each age range find the percent of patients who were readmitted after 30 days and display the results in a bar chart."

I ran the following code and got "Error: n() should only be called in a data context"

cont_table_4<-diabetic_data%>%
  select(age, readmitted)%>%
  filter(readmitted==">30")%>%
  group_by(age)%>%
  summarize(count=n())%>%
  arrange(desc(count()))

I used this almost the exact same format for a question: "Find out which sub-specialty has the most readmissions. Then print the breakdown for that sub-specialty by race." And it worked perfectly. I emailed my instructor a screenshot of the code and error and she said the issue is with count() function call even though the error refers to n(). I don't really know what to do with that information. I have loaded dplyr and plyr, unloaded each of them and tried again with just one of them and I get the same error message. I have looked up many Q&A regarding this error but can't find what I'm looking for. I'm a student just beginning to learn R and any help is appreciated!

  • 4
    Please us `dput` to show a subset of your data, The last line seems to be the issue `arrange(desc(count))` instead of `count()` – akrun Nov 17 '19 at 19:07

1 Answers1

2

Issue would be the count() as a function instead of the 'count' column created before the last line

library(dplyr)
diabetic_data%>%
  select(age, readmitted)%>%
  filter(readmitted==">30")%>%
  group_by(age)%>%
  summarize(count=n())%>%
  arrange(desc(count))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I'm not sure I understand. What needs to be changed? – Leigh Anne Robinson Nov 17 '19 at 19:39
  • 2
    @LeighAnneRobinson I am answering only based on the code you showed. In your code, the last line is `count()` which is a function and not the column in `summarise` step. It is changed to `count` – akrun Nov 17 '19 at 19:41
  • @LeighAnneRobinson If the errorr is happening before the `arrange` step, may be you don't have any rows after the `filter` step. What is the output from `diabetic_data%>% select(age, readmitted)%>% filter(readmitted==">30")` Are you getting any rows? – akrun Nov 17 '19 at 19:44
  • I get a table with 106,635 observations of 2 variables. It is just each time a given age range is associated with >30. I just did cont_table_4$age[1] and it returned the age range 10-20 and all of the levels for age. I'm not sure I trust this is the correct answer. – Leigh Anne Robinson Nov 17 '19 at 20:10
  • 1
    @LeighAnneRobinson As I mentioned in the comments, please show a small reprodcucible examplee and expected output. It would make things faster – akrun Nov 17 '19 at 20:28