[R] recode the same subset of variables in several list elements

Simon Kiss sjkiss at gmail.com
Mon Apr 6 16:33:13 CEST 2015


Hi Jim, So that does the rescale part very efficiently. But I’d like to know how to do that on each list element using lapply or llply.  I have about 4 data frames and a few other recodes to do so automating would be nice, rather than applying your code to each individual list element.
simon
> On Apr 2, 2015, at 6:30 PM, Jim Lemon <drjimlemon at gmail.com> wrote:
> 
> Hi Simon,
> How about this?
> 
> library(plotrix)
> revlist<-grep("i",names(df),fixed=TRUE)
> df[,revlist]<-sapply(df[,revlist],rescale,c(3,1))
> 
> Jim
> 
> 
> On Fri, Apr 3, 2015 at 6:30 AM, Simon Kiss <sjkiss at gmail.com <mailto:sjkiss at gmail.com>> wrote:
> Hi there: I have a list of data frames with identical variable  names.  I’d like to reverse scale the same variables in each data.frame.
> I’d appreciate any one’s suggestions as to how to accomplish this. Right now, I’m working with the code at the very bottom of my sample data.
> Thanks, Simon Kiss
> 
> #Create data.frame1
> df<-data.frame(
>   ivar1=sample(c(1,2,3), replace=TRUE, size=100),
>   ivar2=sample(c(1,2,3), replace=TRUE, size=100),
>   hvar1=sample(c(1,2,3), replace=TRUE, size=100),
>   hvar2=sample(c(1,2,3), replace=TRUE, size=100),
>   evar1=sample(c(1,2,3), replace=TRUE, size=100),
>   evar2=sample(c(1,2,3), replace=TRUE, size=100)
>   )
> 
> #data.frame2
>   df1<-data.frame(
>     ivar1=sample(c(1,2,3), replace=TRUE, size=100),
>     ivar2=sample(c(1,2,3), replace=TRUE, size=100),
>     hvar1=sample(c(1,2,3), replace=TRUE, size=100),
>     hvar2=sample(c(1,2,3), replace=TRUE, size=100),
>     evar1=sample(c(1,2,3), replace=TRUE, size=100),
>     evar2=sample(c(1,2,3), replace=TRUE, size=100)
>   )
> 
> #List
> list1<-list(df, df1)
> #vector of first variables I’d like to recode
> i.recodes<-grep('^i.', names(df), value=TRUE)
> #Vector of second variables to recode
> e.recodes<-grep('^e.', names(df), value=TRUE)
> 
> #Set up RESCALE function from RPMG package
> RESCALE <- function (x, nx1, nx2, minx, maxx)
> { nx = nx1 + (nx2 - nx1) * (x - minx)/(maxx - minx)
>   return(nx)
> }
> 
> #This is what I’m playing around with
> test<-lapply(list1, function(y) {
>   out<-y[,i.recodes]
>   out<-lapply(out, function(x) RESCALE(x, 0,1,1,6))
>   y[,names(x)]<-out
> })
>         [[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org <mailto:R-help at r-project.org> mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help <https://stat.ethz.ch/mailman/listinfo/r-help>
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html <http://www.r-project.org/posting-guide.html>
> and provide commented, minimal, self-contained, reproducible code.
> 


	[[alternative HTML version deleted]]



More information about the R-help mailing list