I just read textbook from Benjamin, Modern Data Science with R. At the page 180, I find the useful function tally() similar to table() or some crosstable function. But I can't reproduce this function in my r.
The author uses this function like this waytally(income_dtree ~ income, data = train, format = "count").
I simulate an example, but fail.
library(dplyr)
data_frame( x = rnorm(100), y = c(rep("A",50),rep("B",50))
) %>% tally(~y)The warning message is Error in summarise_impl(.data, dots) : Evaluation error: invalid 'type' (language) of argument.
Does anyone know how to use it?
Thx for @ycw. The answer is here.
library(tidyverse)
library(mosaic)
data_frame( x = rnorm(100), y = c(rep("A",50),rep("B",50)), z = c(rep("C",70),rep("D",30)),
) %>% tally(~ y + z, data = .) z
y C D A 50 0 B 20 30And the users have to add the data = . in the tally() even they use pipes.
1 Answer
This is probably what you want:
library(dplyr)
data_frame( x = rnorm(100), y = c(rep("A",50),rep("B",50))) %>% group_by(y) %>% tally()
# A tibble: 2 x 2 y n <chr> <int>
1 A 50
2 B 50Which is the same as the follows
data_frame( x = rnorm(100), y = c(rep("A",50),rep("B",50))) %>% count(y)
# A tibble: 2 x 2 y n <chr> <int>
1 A 50
2 B 50Or this
data_frame( x = rnorm(100), y = c(rep("A",50),rep("B",50))) %>% group_by(y) %>% summarise(n = n())
# A tibble: 2 x 2 y n <chr> <int>
1 A 50
2 B 50 3