【问题标题】:can't get the object name, when coerce object into xts将对象强制转换为 xts 时无法获取对象名称
【发布时间】:2014-01-29 12:18:59
【问题描述】:

我编写了接受时间序列对象的函数,我想将输入数据强制转换为 xts 格式,但是当我这样做时, deparse(substitute()) 会出现问题,它应该返回对象的名称。

重现错误的代码:

library(xts)
data(sample_matrix)
matrixObj=sample_matrix

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

myFunc(matrixObj)

[1] "matrixObj" #这就是我想要的。

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

myFunc2(matrixObj)

[1] "结构(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, " ...缩写...

【问题讨论】:

    标签: r xts


    【解决方案1】:

    这是因为您正在修改函数中的对象,而不是因为对象的类型。将 xts 传递给 myFunc 可提供所需的结果

    library(xts)
    data(sample_matrix)
    matrixObj=sample_matrix
    
    xtsObj=as.xts(sample_matrix)
    
    myFunc=function(data){
    
      print(deparse(substitute(data)))  
    }
    
    myFunc(xtsObj)
    #[1] "matrixObj"
    

    此外,在函数中为 xts 对象使用不同的变量名或在获取变量名后进行强制转换都可以:

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 2017-05-29
      • 2012-08-29
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      • 2012-05-30
      相关资源
      最近更新 更多