[R] Converting strings into data frame column names

R. Michael Weylandt michael.weylandt at gmail.com
Wed Jan 25 01:56:21 CET 2012


Yes, I think you are overcomplicating: it's perfectly valid to
subscript by names. (In fact, it's generally preferred to trying to
use the $ for programming because it's so much more flexible) I.e.,

lapply( phList, function(df) get(df)[, c("ID", "DATE_DISPENSED",
"TG_NAME1", "TG_NAME2", "TG_NAME3")] )

This will go through each element of phList, get the object by that
name, and pull out the columns with the given names. Then it will
return to you a list with the results of each iteration.

Alternatively, if you have a list of the data.frame()s, you can just
pass that to lapply and drop the "get" call.

Does that help? Sorry if not -- I had a little bit of trouble
deciphering your code.

Michael

On Tue, Jan 24, 2012 at 7:08 PM, dthomas
<dyfed.thomas at midlandshn.health.nz> wrote:
> Hi all,
>
> I want to loop through a series of data frames and append them into one data
> frame, however I do not want all columns of the original data frames to be
> in the new data frame. I have the following code:
>
> phList<-c('ph2010','ph2009','ph2008','ph2007','ph2006') #Name of original
> data frames
>
> for (i in phList) {
>
> x<-c(paste(i,"$ID",sep=""),paste(i,"$DATE_DISPENSED",sep=""),paste(i,"$TG_NAME1",sep=""),
> paste(i,"$TG_NAME2",sep=""),paste(i,"$TG_NAME3",sep="")) # I may be over
> complicating things here!?
>
> phNew<-rbind(phNew,(data.frame(ID=get(x[1]), DATE_DISPENSED=get(x[2]),
> TG_NAME1= get(x[3]),  TG_NAME2=get(x[4]), TG_NAME3=get(x[5]))))
> }
>
> The error i get is that the columns for extration are not recognised as
> objects which i understand. What i need resolving is how do i get around
> this so that each column desired is extracted from the original data frames?
> Is there a way to make the string (where my over complicating note is) of
> the column name into the column name as get() does not work as I have it.
>
> Your help is much appreciated,
> D
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Converting-strings-into-data-frame-column-names-tp4325870p4325870.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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