[R] select columns from dataframe

Erik Iverson eriki at ccbr.umn.edu
Fri Jul 9 20:37:20 CEST 2010



Jonathan Flowers wrote:
> Hi,
> 
> I would like to extract columns from a dataframe using a vector of desired
> column names.
> 
> The following working example uses the select argument in the subset
> function to accomplish what I am trying to do.  Is there a better solution?

This is very much "Introduction to R" stuff.

A word of warning: both 'data' and 'colnames' are built-in functions, so 
  you may not want to call your variables those things to avoid confusion.

After your definitions below, try:

 > data[colnames]
 > data$col1
 > data$col3
 > data[["col1"]]
 > data[["col3"]]

compare the previous two with:

 > data["col1"]
 > data["col3"]

> 
> Thanks.
> 
> #my data
> data <- data.frame("col1"=c(1,2,3),"col2"=c("A","B","C"),"col3"=c(4,5,6))
> 
> #names of desired columns
> colnames <- c("col1","col3")
> 
> fun <- function(colname,dframe){
>     nframe <- subset(dframe,select=colname)
>     vec <- nframe[,1]
>     return(vec)
> }
> 
> fun(colnames[1],data)
> fun(colnames[2],data)
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list