Rob Tala
Rob Tala

Reputation: 13

How do I assign the argument of one of my functions as a variable name in R?

I wrote the following function:

rename.fun(rai,pred){
assign('pred',rai)
return(pred) }

I called it with the arguments rename.fun(k2e,k2e_cat2) and it returns the object I want but it is named pred.

The point of this function is to assign the object I define as rai to the object I define as pred. So rename k2e to k2e_cat2.

I am new to R but I am a SAS programmer. This is a very simple task with the SAS macro processor but I cant seem to figure it out in R

EDIT:

In SAS I would do the following:

%macro rename_fun(rai=) ;

data output (rename=(&rai.=&rai._cat2));
set input;
run;

%mend;

Essentially, I want to add the suffix _cat2 to a bunch of variables, but they need to be in a function call. I know this seems odd but its for a specific project at work. I am new to R so I apologize if this seems silly.

Upvotes: 1

Views: 112

Answers (1)

Mike H.
Mike H.

Reputation: 14360

Since you say that you want to rename several columns in a data.frame you could simple do this by using a function that takes a data.frame and a list of column names to rename:

add_suffix_cat2 <- function(df, vars){ 
                      names(df)[match(vars, names(df))] <- paste0(vars, "_cat2") 
                      return(df) 
                   }

Then you can call the function like:

mydf <- mtcars
res <- add_suffix_cat2(mydf, c("hp","mpg"))

If you wanted to make the suffix customizable that's simlpe enough to do by adding another parameter to the function.

Upvotes: 1

Related Questions