R语言 从因子列绘制主效应图的更优雅的方法?

ny6fqffe  于 2023-09-27  发布在  其他
关注(0)|答案(1)|浏览(133)

我有统计分析应用程序,并添加多因素方差分析。
接下来的MRE就是我想要的。给定两个因子和一个响应变量,它可以生成一个双向交互作用线图和一个主效应箱线图。
问题是代码感觉很恶心,尤其是主要效果情节代码。我觉得应该有更优雅的方式来做到这一点。

library(ggplot2)

data<-mtcars#could be anything

#Interaction plot
factor_col<-c(2,10)#user inputs
data_col<-4#user inputs

plot_data<-data[c(factor_col,data_col)]#reduced data set

factor_col2<-1:(ncol(plot_data)-1)#columns of factors in reduced data set
data_col2<-ncol(plot_data)#column of data in reduced data set
plot_data[factor_col2]<-lapply(plot_data[factor_col2],factor)#make factors

x_name<-sym(names(plot_data)[1])#factor on x-axis
lines_name<-sym(names(plot_data)[2])#factor that will be different lines
data_name<-sym(names(plot_data)[3])#name of the data column

ggplot(data=plot_data,aes(x=!!x_name,y=!!data_name,color=!!lines_name,group=!!lines_name,linetype=!!lines_name,shape=!!lines_name))+
  stat_summary(fun = mean,geom="line")+
  stat_summary(fun = mean,geom="point")


#main effects
plot_data2<-rbind(plot_data,plot_data)#doubling the data for facet
name_A<-names(plot_data)[1]#Name of factor for facet
name_B<-names(plot_data)[2]#Name of factor for facet
rows<-nrow(plot_data)
plot_data2$facet<-c(rep(name_A,rows),rep(name_B,rows))#Add single column of facet names

plot_data2$level[plot_data2$facet==name_A]<-paste0(names(data)[factor_col[1]]," = ",data[,factor_col[1]])#level names for first factor
plot_data2$level[plot_data2$facet==name_B]<-paste0(names(data)[factor_col[2]]," = ",data[,factor_col[2]])#level names for second factor
plot_data2$level<-factor(plot_data2$level)#make levels a factor

ggplot(data = plot_data2,aes(y=!!data_name))+
  geom_boxplot(aes(x=level))+
  stat_summary(aes(x=level),fun="mean",geom="point")+
  facet_wrap(vars(facet),scales="free")
ffscu2ro

ffscu2ro1#

这里有一个主效应图的更短的方法,我相信可以改进,特别是基于位置的y变量的选择。

library(tidyverse)
data_col_name <- names(select(mtcars, {{data_col}}))
mtcars %>%
  pivot_longer(factor_col) %>%
  mutate(level = paste(name, "=", value)) %>%
ggplot(aes(y=!!sym(data_col_name))) +
  geom_boxplot(aes(x=level))+
  stat_summary(aes(x=level),fun="mean",geom="point")+
  facet_wrap(vars(name),scales="free")

第一部分也有类似的情况,但我认为“按位置选择”部分的语法更整洁。

ggplot(mtcars, aes(x = !!sym(names(select(mtcars, factor_col[1]))),
                   y = !!sym(names(select(mtcars, data_col))),
                   color = factor(!!sym(names(select(mtcars, factor_col[2])))),
                   linetype = factor(!!sym(names(select(mtcars, factor_col[2])))))) +
  stat_summary(fun = mean,geom="line")+
  stat_summary(fun = mean,geom="point")

相关问题