maximusdooku
maximusdooku

Reputation: 5512

How can I pass column names in an R function?

I want to create a dataframe inside the function that is a selection of columns in the dataframe d

QPP<-function(dat,xvar,yvar){
  varx <<- dat[,c(xvar)]
  vary <<- dat[,c(yvar)]
  a <- cbind(varx,vary) 
  a <- as.data.frame(a)
  #Perform some operations
}

QPP(dat=d,xvar = area,yvar = f.ecdf)

But I get an error message:

Error in eval(expr, envir, enclos) : argument is missing, with no default

  1. How can I fix this?
  2. Alternatively, can I do the selection of column names in one step instead of selecting and then cbinding it? I am not sure how to pass the column names.

    dput(droplevels(head(d,10)))
    structure(list(area = c(96.8656, 96.8656, 562.0274, 117.5855, 
    117.5855, 117.5855, 117.5855, 117.5855, 117.5855, 117.5855), 
    tp = c(1.5, 1, 0.5, 4.5, 6, 8.25, 4.25, 5.75, 10.75, 20.25
    ), f.ecdf = c(0.887918176006819, 0.812380140634988, 0.760387811634349, 
    0.0372895802258683, 0.00809716599190283, 0.0310036224163648, 
    0.300660558278287, 0.441721713189857, 0.152354570637119, 
    0.386852759428937)), .Names = c("area", "tp", "f.ecdf"), row.names = c(NA, 
    -10L), class = c("data.table", 
    "data.frame"))
    

Upvotes: 2

Views: 7293

Answers (1)

saurav shekhar
saurav shekhar

Reputation: 606

Your function is perfectly fine. There is issue with the way you are passing the argument. You are supposed to pass strings as variable names.

Try this QPP(dat=d,xvar = "area" ,yvar = "f.ecdf")

Now, this happens because if you notice df[,c("col_name")] the argument "col_name" is string

Regarding your question 2: This is how you can do it one step without using cbind

QPP<-function(dat,xvar,yvar)
{
colnames<- c(xvar, yvar)
new_df <<- dat[, c(colnames)]
}

QPP(dat=d,xvar = "area" ,yvar = "f.ecdf")

Upvotes: 3

Related Questions