2

I am getting errors when I try to enter the code for a couple of answers to this question. The code is very simple, yet I still get errors.

When entering this code I get an error message:

 library(dplyr)
 mtcars %>% 
+   group_by(cyl, gear) %>% 
+   summarise(n = n())

Error: This function should not be called directly

Also, this doesn't work either:

count(mtcars, cyl, gear)

Error in count(mtcars, cyl, gear) : object 'gear' not found

Neither does this:

 mtcars %.% 
+   dplyr::group_by(cyl, gear) %.%
+   dplyr::summarise(length(gear))

Error in mtcars %.% dplyr::group_by(cyl, gear) %.% dplyr::summarise(length(gear)) : could not find function "%.%"

However, this does work:

mtcars %>% group_by(cyl, gear) %>% do(data.frame(nrow=nrow(.)))

Can anyone shed some light on what is going wrong? Thanks!

JJJ
  • 1,009
  • 6
  • 19
  • 31

1 Answers1

0

Separate commands should go on separate lines. Otherwise, separate them with a semicolon. Next, %>% is a piping command. It takes the output from the left side and pipes it into the input of the next function. It lets you chain multiple commands together. Thus, the + is not only unnecessary, it adds another error.

Hence, library(dplyr) mtcars %>% + group_by(cyl, gear) %>% + summarise(n = n()) should become library(dplyr); mtcars %>% group_by(cyl, gear) %>% summarise(n = n()) or more clearly:

    library(dplyr)
    mtcars %>% 
      group_by(cyl, gear) %>%
        summarise(n = n())

EDIT Syntax varies by package. I would read vignettes to get a better understanding of how the package works.

A Duv
  • 393
  • 1
  • 17