【问题标题】:Getting a variable to pass into function in R (ggplot2)获取变量以传递给R中的函数(ggplot2)
【发布时间】:2019-01-19 02:37:15
【问题描述】:

我正在尝试在名为“final”的数据框中的两列数据之间绘制图表。我希望 p 值和 r^2 值显示在图表上。

我正在使用这个函数和代码,但它给了我错误“找不到 y 值”

library(ggplot2)
lm_eqn <- function(final, x, y){
        m <- lm(final[,y] ~ final[,x])

output <- paste("r.squared = ", round(summary(m)$adj.r.squared, digits = 4), " | p.value = ", formatC(summary(m)$coefficients[8], format = "e", digits = 4))
   return(output)
     }

output_plot <- lm_eqn(final, x, y)

p1 <- ggplot(final, aes(x=ENSG00000153563, y= ENSG00000163599)) + geom_point() + geom_smooth(method=lm, se=FALSE) + labs(x = "CD8A", y = "CTLA-4") + ggtitle("CD8 v/s CTLA-4", subtitle = paste("Linear Regression of Expression |", output_plot))

如何让数据 x 和 y 的两列都流过函数,并让图表在图表上打印 p 值和残差值?

提前致谢。

【问题讨论】:

  • see here 提出人们可以帮助解决的 R 问题,包括您的数据的代表性样本

标签: r function variables ggplot2


【解决方案1】:

当您为 output_plot 生成调用函数时,您必须使用与绘图中相同的 ENS... 变量。稍微简化功能后,现在应该可以工作了

   library(stats)
   library(ggplot2)
   lm_eqn <- function(x, y){
     m <- lm(y ~ x)
     output <- paste("r.squared = ", round(summary(m)$adj.r.squared, digits = 4), " | p.value = ", formatC(summary(m)$coefficients[8], format = "e", digits = 4))
     return(output)
   }
   x <-c(1,2,5,2,3,6,7,0)
   y <-c(2,3,5,9,8,3,3,1)
   final <- data_frame(x,y)

   output_plot <- lm_eqn(x, y)

   p1 <- ggplot(final, aes(x=x, y= y)) + geom_point() + geom_smooth(method=lm, se=FALSE) + labs(x = "x", y = "y") + ggtitle("CD8 v/s CTLA-4", subtitle = paste("Linear Regression of Expression |", output_plot)) 

【讨论】:

  • 非常感谢这个工作!但是我有多个图表要使用我的数据框中的各个列,当我使用这个函数时,为什么所有的图表都在顶部报告了相同的值?
  • 确保您在每次绘图之前使用新变量调用 output_plot
猜你喜欢
  • 1970-01-01
  • 2011-02-26
  • 2013-10-08
  • 2013-03-05
  • 2015-12-31
  • 2015-02-24
  • 1970-01-01
  • 2021-07-18
  • 2021-12-12
相关资源
最近更新 更多