尝试创建一个从分位数回归模型中提取所需系数的函数,将其应用于多个变量并编译系数。这是我的功能;
library (quantreg) ## to perform quantile regression
taus <- c(.05,.25,.75, 0.95)
Myfun <- function(varname, data){
y <- data[,varname]
q <- summary(rq(y~x, taus),se="boot")
z <- cbind(q[[1]]$coef[1,1], q[[2]]$coef[1,1], q[[3]]$coef[1,1], q[[4]]$coef[1,1])
}
colnames(z) = c("Q1b", "Q2b","Q3b", "Q4b")
##creating an artificial dataset
set.seed (1988)
x <- rnorm(50,10,1); error1 <- rnorm(50,0,1); error2 <- rnorm(50,0,5)
data <- data.frame(cbind(y1 <- 1+(2*x)+error1, y2 <- 1+(2*x)+error2, x))
Myfun <- function(varname, data){
y <- data[,varname]
q <- summary(rq(y~x, taus),se="boot")
z <- cbind(q[[1]]$coef[1,1], q[[2]]$coef[1,1], q[[3]]$coef[1,1], q[[4]]$coef[1,1])colnames(data) <-c ("y1", "y2", "x")
## apply Myfun for the data
listcoef <- lapply(names(data)[1:2], function(x) Myfun(x, data))
我能够从中得到结果。但是,当我添加时,colnames(data)&lt; - c(“y1”,“y2”,“x”)如下所示,
Myfun <- function(varname, data){
y <- data[,varname]
q <- summary(rq(y~x, taus),se="boot")
z <- cbind(q[[1]]$coef[1,1], q[[2]]$coef[1,1], q[[3]]$coef[1,1], q[[4]]$coef[1,1])
colnames(data) <- c("y1", "y2", "x")
}
作为Myfun的最后一行,我只将列名作为listcoef的结果。请告诉我哪里出错了?
答案 0 :(得分:1)
该函数返回的是上次计算的内容(如果添加此行,则为此处的名称向量)。您可以在函数顶部添加此行:
Myfun <- function(varname, data){
colnames(data) <- c("y1", "y2", "x")
y <- data[,varname]
q <- summary(rq(y~x, taus),se="boot")
z <- cbind(q[[1]]$coef[1,1], q[[2]]$coef[1,1], q[[3]]$coef[1,1], q[[4]]$coef[1,1])
}
或添加return()
语句。
Myfun <- function(varname, data){
y <- data[,varname]
q <- summary(rq(y~x, taus),se="boot")
z <- cbind(q[[1]]$coef[1,1], q[[2]]$coef[1,1], q[[3]]$coef[1,1], q[[4]]$coef[1,1])
colnames(data) <- c("y1", "y2", "x")
return(z)
}