0

There is a dataframe (x) with large number of columns. I want to select columns from it inside a function.

selectcols<-function(dat,xvar,yvar){
  t<-dat[,c(xvar,yvar)] 
}

selectcols(dat=x,xvar = "area",yvar = "y")

Here y and area are two columns. But this is not working. How can I fix it?

9
  • I thiink you don't need a function to select columns. Unless you want to add some criteria with which some columns will be selected. Have a look at this df <-data.frame(a=1:5,b=6:10,c=40:44). df[,c("a","c")] Commented Aug 27, 2015 at 20:37
  • It's a part of a bigger codebase. And I need to do this inside a function. Commented Aug 27, 2015 at 20:37
  • 4
    you need to have a return statement inside the function. Commented Aug 27, 2015 at 20:38
  • This should work: selectcols <- function(d,jx,jy) "["(d,c(jx,jy)) Commented Aug 27, 2015 at 20:42
  • @darwin not necessarily. @maximusdooku Just end your function with t or return(t) . That should to the job. Commented Aug 27, 2015 at 20:42

1 Answer 1

0

I like using dplyr for this

library(dplyr)
selectcols <- function(dat,xvar,yvar){
  t <- dat %>% select(matches(xvar), matches(yvar))
}

x <- data.frame(area = 1:10, y = 11:20, z = LETTERS[1:10])
selection <- selectcols(dat=x, xvar = "area", yvar = "y")
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.