【发布时间】:2018-02-25 16:24:47
【问题描述】:
我的数据:
Subject Test1 Test2 Test3 Test4
1 8 7 1 6
2 9 5 2 5
3 6 2 3 8
4 5 3 1 9
5 8 4 5 8
6 7 5 6 7
7 10 2 7 2
8 12 6 8 1
mydata mydataframe
我做了以下函数来应用于我的数据框的每个列变量,其中包含 4 列:
qqfunc <- function(df,df_var) {
y <- quantile(df$df_var, c(0.25, 0.75))
x <- qnorm( c(0.25, 0.75))
slope <- diff(y) / diff(x)
int <- y[1] - slope * x[1]
ggplot() + aes(sample=df$df_var) + stat_qq(distribution=qnorm) +
geom_abline(intercept=int, slope=slope) + ylab("QQ")
}
当我跑步时
qqfunc(mydataframe, Test1)
出现警告信息:
删除了 1 行包含缺失值 (geom_abline)。
因此,QQ 图没有出现在 pdf 输出文件中。我不确定问题出在解析中还是在函数 ggplot() 中。
PS:
1. 奇怪的是,如果我在函数之外运行以下这些命令,它会起作用:
y <- quantile(mydataframe$Test1, c(0.25, 0.75)) # Find the 1st and 3rd quartiles
x <- qnorm( c(0.25, 0.75)) # Find the matching normal values on the x-axis
slope <- diff(y) / diff(x) # Compute the line slope
int <- y[1] - slope * x[1] # Compute the line intercept # Generate normal q-q plot
ggplot() + aes(sample=mydataframe$Test1) + stat_qq(distribution=qnorm) +
geom_abline(intercept=int, slope=slope) + ylab("QQ Test1")
2.如果我运行这些命令:
qqfunc <- function(df, df_var) {
y <- quantile(df[[df_var]], c(0.25, 0.75))
x <- qnorm( c(0.25, 0.75))
slope <- diff(y) / diff(x)
int <- y[1] - slope * x[1]
ggplot() + aes(sample=df[[df_var]]) + stat_qq(distribution=qnorm) +
geom_abline(intercept=int, slope=slope) + ylab("QQ")
}
qqfunc(mydataframe, Test1)
错误信息:
(function(x, i, exact) if (is.matrix(i)) as.matrix(x)[[i]] else .subset2(x, 中的错误: 找不到对象“Test1”
完整代码:
library(Hmisc)
library(ggplot2)
library(boot)
library(polycor)
library(ggm)
library(gdata)
library(readxl)
library(csvread)
library (plyr)
library(psych)
library(mice)
library(VIM)
library(ez)
library(reshape)
library(multcomp)
library(nlme)
library(pastecs)
library(WRS2)
library(dplyr)
mydata <- read.csv("mydata.csv", header = TRUE) # CSV
mydataframe <- data.frame(mydata)
y <- quantile(mydataframe$Test1, c(0.25, 0.75)) # Find the 1st and 3rd quartiles
x <- qnorm( c(0.25, 0.75)) # Find the matching normal values on the x-axis
slope <- diff(y) / diff(x) # Compute the line slope
int <- y[1] - slope * x[1] # Compute the line intercept # Generate normal q-q plot
ggplot() + aes(sample=mydataframe$Test1) + stat_qq(distribution=qnorm) + geom_abline(intercept=int, slope=slope) + ylab("QQ Test 1")
qqfunc <- function(df, df_var) {
y <- quantile(df[[df_var]], c(0.25, 0.75))
x <- qnorm( c(0.25, 0.75))
slope <- diff(y) / diff(x)
int <- y[1] - slope * x[1]
ggplot() + aes(sample=df[[df_var]]) + stat_qq(distribution=qnorm) +
geom_abline(intercept=int, slope=slope) + ylab("QQ")
}
qqfunc(mydataframe, Test1)
【问题讨论】:
-
你能分享你的数据吗? meta.stackoverflow.com/questions/315885/…
-
问题似乎是
quantile(df$df_var, ...). Try insteadquantile(df[[df_var]], ...)`。 -
主题测试1测试2测试3测试4 1 8 7 1 6 2 9 5 2 5 3 6 2 3 8 4 5 3 1 9 5 8 4 5 8 6 7 5 6 7 7 10 2 7 2 8 12 6 8 1
-
Rui,当我在函数外使用这些命令时,它们运行良好。但是,我只想将这些命令编译成一个函数,以避免为我的数据框的每一列编写它们
-
@Rei:您应该将数据添加到您的问题中,而不是评论中。请阅读我发布的链接