Re: [R] Function to create variables with prefix

From: Uwe Ligges <ligges_at_statistik.tu-dortmund.de>
Date: Tue, 15 Jul 2008 12:06:48 +0200

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.



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. Received on Tue 15 Jul 2008 - 10:22:47 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 18 Jul 2008 - 01:31:57 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive