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

Simon Kiss sjkiss at gmail.com
Thu Apr 2 21:30:46 CEST 2015


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]]



More information about the R-help mailing list