[R] Function to create variables with prefix

Uwe Ligges ligges at statistik.tu-dortmund.de
Tue Jul 15 12:06:48 CEST 2008


Example:

myfunction <- function(mydata, myvariables, prefix="norm_"){
	newnames <- paste(prefix, myvariables, sep="")
	mydata[newnames] <- scale(mydata[myvariables])
	mydata
}

mydata <- data.frame(a=1:2, b=3:2)
myfunction(mydata, c("a", "b"))


Moira Burke wrote:
> Hi.  I'm a new R user and think what I'm trying to do is pretty basic, but
> haven't been able to find the answer in the mailing list archives.  How do I
> write a function that creates new variables in a given data.frame with a
> prefix attached to the variable names?  I do a lot of repetitive logging and
> scaling of variables, and would like a way to consistently generate and name
> versions of the variables.
> 
> The function would take a data.frame, an array of variables, and a prefix
> string.  It performs a transformation on the variables (e.g. logs and
> scales), and creates new variables with the same names as the inputs, but
> with the prefix_string prepended.
> 
> So, a sample call would look like:
> 
> myfunction(mydata, myvariables, "norm_")
> 
> And if myvariables contained variables named "var1", "var2", etc., the
> function would generate:
> 
> mydata$norm_var1
> mydata$norm_var2
> 
> Thanks,
> Moira
> 
> 	[[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.



More information about the R-help mailing list