Dan KS
Dan KS

Reputation: 143

Using functions to change variable names from upper to lower

I'm working with a bunch of SAS datasets and I prefer the variable names to all be lowercase, using read.sas7bdat, but I do it so often I wanted to write a function. This method works fine,

df <- data.frame(ALLIGATOR=1:4, BLUEBIRD=rnorm(4))
names(file1) <- tolower(names(file1))

but when I try to put it into a function it doesn't assign.

lower <- function (df) {names(df) <- tolower(names(df))}
lower(file1)

I know that there is some larger concept that I'm missing, that is blocking me. It doesn't seem to do anything.

Upvotes: 1

Views: 3771

Answers (3)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59980

Here is an answer that I don't recommend using anywhere other than the globalenvironment but it does provide you some convenient shorthand. Basically we take care of the assignment inside the function, overwriting the object passed to it. Short-hand for you, but please be careful about how you use it:

tl <- function(x){
  ass <- all.names(match.call()[-1])
  assign( ass , setNames( x , tolower(names(x))) , env = sys.frame(sys.parent()) )
}

#  This will 'overwrite' the names of df...    
tl(df)

#  Check what df now looks like...
df
  alligator   bluebird
1         1  0.2850386
2         2 -0.9570909
3         3 -1.3048907
4         4 -0.9077282

Upvotes: 0

Karl Forner
Karl Forner

Reputation: 4414

Arguments in R are passed by copy. You have to do:

lower <- function (df) {
  names(df) <- tolower(names(df))
  df
}
file1 <- lower(file1)

Upvotes: 7

Mayou
Mayou

Reputation: 8848

Although I don't see why you would do this rather than simply : names(df) <- tolower(names(df)), I think you should do:

 lower <- function (x) {tolower(names(x))}
 names(df) <- lower(df)

Upvotes: 3

Related Questions