首页 > 解决方案 > 函数内 set_tag() 时未找到 AzureRMR 对象

问题描述

运行set_my_tag(resources_to_tag)给出错误

eval(expr, p) 中的错误:找不到对象“资源”

library(tidyverse)
library(AzureRMR)
#> Warning: package 'AzureRMR' was built under R version 3.6.3
#> 
#> Attaching package: 'AzureRMR'
#> The following object is masked from 'package:purrr':
#> 
#>     is_empty

set_my_tag <- function(resources_to_tag) {
  
  for (i in 1:nrow(resources_to_tag)) {
    resource <- resources_to_tag[i, ]
    
    az$
      get_subscription(resource$subscriptionid)$
      get_resource_group(resource$resourcegroup)$
      get_resource(type = resource$type, name = resource$name)$
      set_tags(MYTAG = resource$new_tag)
  }
  
}
resources_to_tag <-
  tribble(
    ~name, ~resourcegroup, ~subscriptionid, ~type, ~new_tag,
    "resource name", "resource group", "subscription id", "resource type", "new tag"
  )

reprex 包于 2021-02-04 创建(v0.3.0)

虽然我执行以下操作(不将我的代码放入函数中),但一切正常。

    resource <- resources_to_tag[1, ]

    az$
      get_subscription(resource$subscriptionid)$
      get_resource_group(resource$resourcegroup)$
      get_resource(type = resource$type, name = resource$name)$
      set_tags(MYTAG = resource$new_tag)

此外,这是最奇怪的部分,如果我set_tag()set_my_tag()函数中删除它可以正常工作:

set_my_tag <- function(resources_to_tag) {
  
  for (i in 1:nrow(resources_to_tag)) {
    resource <- resources_to_tag[i, ]
    
    az$
      get_subscription(resource$subscriptionid)$
      get_resource_group(resource$resourcegroup)$
      get_resource(type = resource$type, name = resource$name)
  }
}

set_my_tag(resources_to_tag)

你知道有什么问题吗?

标签: razure

解决方案


这是因为set_tags用于match.call获取未评估的标记名。当您向它传递一个表达式时,必须评估该表达式以获取实际标记。set_tags由于必须处理父框架,这会在内部遇到问题。

一种解决方法是eval(substitute(*))在调用之前强制计算表达式set_tags

set_my_tag2 <- function(resources_to_tag)
{
    for(i in seq_len(nrow(resources_to_tag)))
    {
        resource <- resources_to_tag[i, ]
        tag <- resource$newtag
        obj <- az$
            get_subscription(resource$subscriptionid)$
            get_resource_group(resource$resourcegroup)$
            get_resource(type = resource$type, name = resource$name)
        eval(substitute(obj$set_tags(my_tag=.value), list(.value=resource$new_tag)))
    }
}

我会在下一个 AzureRMR 版本中解决这个问题。事后看来,最好避免所有这些 NSE 业务......


推荐阅读