Hi I want to extract columns from a data frame using a vector with the desired column names. This short example uses the select argument in the subset function to accomplish what I am trying to do. Is there a better solution? #names of desired columns colnames <- c("col1","col3") #my data data <- data.frame("col1"=c(1,2,3),"col2"=c("A","B","C"),"col3"=c(4,5,6)) 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]]
How about data[,colnames(data)%in%colnames] -----Original Message----- From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On Behalf Of Jonathan Flowers Sent: Friday, July 09, 2010 11:27 AM To: r-help at r-project.org Subject: [R] select columns from vector of column names Hi I want to extract columns from a data frame using a vector with the desired column names. This short example uses the select argument in the subset function to accomplish what I am trying to do. Is there a better solution? #names of desired columns colnames <- c("col1","col3") #my data data <- data.frame("col1"=c(1,2,3),"col2"=c("A","B","C"),"col3"=c(4,5,6)) 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.
How about data[ , colnames] Or data[ , colnames[1]] data[ , colnames[2]] -Don On 7/9/10 11:27 AM, "Jonathan Flowers" <jonathanmflowers at gmail.com> wrote:> Hi > > I want to extract columns from a data frame using a vector with the desired > column names. > > This short example uses the select argument in the subset function to > accomplish what I am trying to do. Is there a better solution? > > #names of desired columns > colnames <- c("col1","col3") > > #my data > data <- data.frame("col1"=c(1,2,3),"col2"=c("A","B","C"),"col3"=c(4,5,6)) > > 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. >-- Don MacQueen Environmental Protection Department Lawrence Livermore National Laboratory 925 423-1062