I created a simple pivot table in the dplyr
package in R. Here is my working example:
library(dplyr)
mean_mpg <- mean(mtcars$mpg)
# creating a new variable that shows that Miles/(US) gallon is greater than the mean or not
mtcars <-
mtcars %>%
mutate(mpg_cat = ifelse(mpg > mean_mpg, 1,0))
mtcars %>%
group_by(as.factor(cyl)) %>%
summarise(sum=sum(mpg_cat),total=n()) %>%
mutate(percentage=sum*100/total)
Now, I want to write a function to reuse this code:
get_pivot <- function(data, predictor,target) {
result <-
data %>%
group_by(as.factor(predictor)) %>%
summarise(sum=sum(target),total=n()) %>%
mutate(percentage=sum*100/total);
print(result)
}
but I receive the following error:
Error in is.factor(x) : object 'cyl' not found
I also tried
get_pivot(mtcars, "cyl", "mpg_cat" )
but it did not work.
What should I do?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…