Enigma
Enigma

Reputation: 139

Passing column names from a function to use it in lapply

Trying to create a function to extract required coefficients from a quantile regression model, apply it for more than one variable and compile coefficients. Here is my function;

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))

I am able to get the results as I wanted from this. However, when I add, colnames(data) <- c("y1", "y2", "x") as below,

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")
}

as last line in Myfun, I get only the column names as results from listcoef. Please let me know where am I going wrong?

Upvotes: 0

Views: 432

Answers (1)

cmbarbu
cmbarbu

Reputation: 4534

What is returned by the function is what is last computed (here your vector of names if you add this line). You can either add this line at the top of your function :

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])
}

or add a return() statement.

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)
}

Upvotes: 1

Related Questions