On Jun 14, 2013, at 6:34 AM, Arman Eshaghi wrote:

> Dear all,
> 
> I have different data frames for which I would like to modify names of each
> column such that the new name would include the name of the first column
> added to the name of other columns; I came up with the following code.
> Nothing changes when I run the following code. I would be grateful if
> someone could help me.
> 
> All the best,
> -Arman
> 
> rename_columns <- function(dataset) {
> for (i in 2:(ncol(dataset))) {names(dataset)[i] <- paste(names(dataset)[1],
> names(dataset)[i], sep="_")
> }
> }
> 
> rename_columns(dataset) %nothing happens!

A bit of commentary: Something did happen. It's just that you didn't do 
anything with _what_ happened. The copy of the 'dataset'-object got modified 
but you never returned it from the function, and and also didn't reassign it to 
the original 'dataset'. Functions return their last assignment. In the case of 
the 'for'-function, it somewhat surprisingly returns a NULL. It is a rather odd 
function in the functional R world, since its main role in life is doing things 
by side-effects, and so when used inside functions has seemingly paradoxical 
behavior. Check your results with:

rename_columns <- function(dataset) {
for (i in 2:(ncol(dataset))) {names(dataset)[i] <- paste(names(dataset)[1],
names(dataset)[i], sep="_")
}
dataset}

dataset <- rename_columns(dataset)

>       [[alternative HTML version deleted]]

And do learn to post in plain text.
> 
> ______________________________________________
> R-help@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.

David Winsemius
Alameda, CA, USA

______________________________________________
R-help@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.

Reply via email to