我正在尝试编写一个函数来为我提供两个变量的数据透视表。在这里扩展我的问题,我想包括预测变量和目标之间关系的卡方检验的 p 值。我应该如何更改功能?
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)
# Note: needs installation of rlang 0.4.0 or later
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)
}
这是我的工作示例:
mtcars %>%
group_by(as.factor(cyl)) %>%
summarise(sum=sum(mpg_cat),total=n(),
pvalue= chisq.test(as.factor(.$mpg_cat), as.factor(.$cyl))$p.value) %>%
mutate(percentage=sum*100/total)
我尝试了以下功能,但没有奏效。
get_pivot <- function(data, predictor,target) {
result <-
data %>%
group_by( {{ predictor }} ) %>%
summarise(clicks=sum( {{ target }} ),total=n(),
pvalue= chisq.test(.$target, .$predictor)$p.value) %>%
mutate(percentage=clicks*100/total);
print(result)
}