Jon Minton
2007-Apr-23 11:30 UTC
[R] automating merging operations from multiple dataframes
Hi, I have a set of dataframes names AINDSLIM, BINDSLIM, CINDSLIM ... NINDSLIM In each dataframe I want to extract two variables, “pid” and “{w}region”, where {w} means “a”, “b”, “c”, ...”n” At the moment my code looks like:> PidRegion <- data.frame(pid=XWAVEID$pid)> this.region <- AINDSLIM[,c("pid", "aregion")]> PidRegion <- merge(PidRegion, this.region, by="pid", all=T)> this.region <- BINDSLIM[,c("pid", "bregion")]> PidRegion <- merge(PidRegion, this.region, by="pid", all=T)> this.region <- CINDSLIM[,c("pid", "cregion")]...> this.region <- NINDSLIM[,c("pid", "nregion")]> PidRegion <- merge(PidRegion, this.region, by="pid", all=T)But surely there’s a way to automate this? Any suggestions? Jon Minton Checked by AVG Free Edition. 22/04/2007 20:18 [[alternative HTML version deleted]]
Vladimir Eremeev
2007-Apr-23 12:24 UTC
[R] automating merging operations from multiple dataframes
Consider sapply and get. There might be something like the following (untested) fn<-function(l){ # l is supposed to be a letter. Errors will occur otherwise. #constructing names dfr.name<-paste(toupper(l),"INDSLIM",sep="") column.name<-paste(tolower(l),"region",sep="") #retrieving data from the environment this.reg<-get(dfr.name)[,c("pid",column.name)] #merging data frames. #please, note "<<-". This assigns the value to the variable in this function environment's parent frame PidRegion<<-merge(PidRegion,this.reg,by="pid",all=TRUE) # this should help avoiding too much output invisible(PidRegion) } PidRegion <- data.frame(pid=XWAVEID$pid) sapply(letters[1:14],FUN=fn) Jon Minton wrote:> > Hi, > > I have a set of dataframes names AINDSLIM, BINDSLIM, CINDSLIM ... NINDSLIM > In each dataframe I want to extract two variables, ?pid? and ?{w}region?, > where {w} means ?a?, ?b?, ?c?, ...?n? > At the moment my code looks like: >> PidRegion <- data.frame(pid=XWAVEID$pid) >> this.region <- AINDSLIM[,c("pid", "aregion")] >> PidRegion <- merge(PidRegion, this.region, by="pid", all=T) >> this.region <- BINDSLIM[,c("pid", "bregion")] >> PidRegion <- merge(PidRegion, this.region, by="pid", all=T) >> this.region <- CINDSLIM[,c("pid", "cregion")] > ... >> this.region <- NINDSLIM[,c("pid", "nregion")] >> PidRegion <- merge(PidRegion, this.region, by="pid", all=T) > > But surely there?s a way to automate this? > > Any suggestions? > Jon Minton >-- View this message in context: http://www.nabble.com/automating-merging-operations-from-multiple-dataframes-tf3630723.html#a10139026 Sent from the R help mailing list archive at Nabble.com.