[R] Renaming Within A Function

jim holtman jholtman at gmail.com
Thu Dec 22 20:42:13 CET 2011


Why do you want to create a variable within the function since it will
disappear after the return.  Is there a reason for that?  Here is one
way of getting the names by just using them on the cbind.

Also you are create a 'matrix' and 'names' is not appropriate for that
type of object.

> # Test Function
> myfunc <-function(var){
+  d   = c(1,2,3,4,5)
+  dts = seq(as.Date("2011-01-01"),by="month",length.out=length(d))
+
+  assign(paste(var,".df",sep=""), cbind(Dates = dts, Data = d))
+  get(paste(var,".df",sep=""))  # return object
+ }
>
> # Call Function
> myfunc("X")
     Dates Data
[1,] 14975    1
[2,] 15006    2
[3,] 15034    3
[4,] 15065    4
[5,] 15095    5


To get the same return value, you could:

> # Test Function
> myfunc <-function(var){
+  d   = c(1,2,3,4,5)
+  dts = seq(as.Date("2011-01-01"),by="month",length.out=length(d))
+
+  cbind(Dates = dts, Data = d)
+ }
>
> # Call Function
> myfunc("X")
     Dates Data
[1,] 14975    1
[2,] 15006    2
[3,] 15034    3
[4,] 15065    4
[5,] 15095    5
>


On Thu, Dec 22, 2011 at 2:15 PM, Pete Brecknock <Peter.Brecknock at bp.com> wrote:
> I am trying to rename column names in a dataframe within a function. I am
> seeing an error (listed below) that I don't understand.
>
> Would be grateful of an explanation of what I am doing wrong and how I
> should rewrite the function to allow me to be able to rename my variables.
>
> Thanks.
>
> # Test Function
> myfunc <-function(var){
>  d   = c(1,2,3,4,5)
>  dts = seq(as.Date("2011-01-01"),by="month",length.out=length(d))
>
>  assign(paste(var,".df",sep=""), cbind(dts, d))
>
>  names(get(paste(var,".df",sep="")))  <- c("Dates","Data")
> }
>
> # Call Function
> myfunc("X")
>
> # Error Message
> Error in names(get(paste(var, ".df", sep = ""))) <- c("Dates", "Data") :
>  could not find function "get<-"
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Renaming-Within-A-Function-tp4226368p4226368.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.



More information about the R-help mailing list