Question

I wrote functions which accept time series object, I want to coerce the input data into xts format, but when I do that, deparse(substitute()) become problematic, it should return the name of the object.

codes to reproduce the error:

library(xts)
data(sample_matrix)
matrixObj=sample_matrix

myFunc=function(data){
  print(deparse(substitute(data)))  
}

myFunc(matrixObj)

[1] "matrixObj" #This is what I want.

myFunc2=function(data){
  data=as.xts(data)#add this line to coerce data into xts format
  print(deparse(substitute(data)))  
}

myFunc2(matrixObj)

[1] "structure(c(50.0397819115463, 50.2304961977954, 50.420955209067, "
[2] "50.3734680543285, 50.2443255196795, 50.1321122972067, 50.0355467742705, "
[3] "49.9948860954217, 49.9122834457642, 49.8852887132391, 50.2125821224916, "
[4] "50.3238453485025, 50.4635862266585, 50.6172355897254, 50.620241173435, "
[5] "50.7414981135498, 50.4805101188755, 50.4138129108681, 50.3532310036568, "
[6] "50.1618813949374, 50.3600836896748, 50.0396626712588, 50.1095259574076, "
[7] "50.2073807897632, 50.1600826681477, 50.0604060861532, 49.9658575219043, " ...abbreviated...

Was it helpful?

Solution

It's because you're modifying the object in your function, not because of the type of the object. Passing an xts into myFunc provides the desired result

library(xts)
data(sample_matrix)
matrixObj=sample_matrix

xtsObj=as.xts(sample_matrix)

myFunc=function(data){

  print(deparse(substitute(data)))  
}

myFunc(xtsObj)
#[1] "matrixObj"

In addition, either using a different variable name for the xts object in your function or doing the coercion after getting the variable name would work:

library(xts)
data(sample_matrix)
matrixObj=sample_matrix

#use a different variable name for the xts object
myFunc3=function(data){
  xtsdata=as.xts(data)
  print(deparse(substitute(data)))  

}

myFunc3(matrixObj)
#[1] "matrixObj"

#get the name before doing the coercion
myFunc4=function(data){
  print(deparse(substitute(data)))  
  data=as.xts(data)

}

myFunc4(matrixObj)
#[1] "matrixObj"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top