代码之家  ›  专栏  ›  技术社区  ›  elliot

如何在粘贴中使用对象名?

  •  1
  • elliot  · 技术社区  · 8 年前

    node_attributes <- function(i){ #i is dataframe
    j <- network(i)
    ##some other function stuff##
    (i,'network',sep = '_')) <- j 
    }
    

    其想法是创建“添加网络”到 一、 变量,即数据帧。如果我的原始数据帧是 foo\u bar\u数据 ,我的输出将是: foo\u bar\u data\u网络

    2 回复  |  直到 8 年前
        1
  •  1
  •   Gregor de Cillia    8 年前

    可以使用 deparse(substitute(argname)) .

    func <- function(x){
      depsrse(substitute(x))
    }
    
    func(some_object)
    ## [1] "some_object"
    

    node_attributes <- function(i){
      output_name <- paste(deparse(substitute(i)), 'network', sep = '_')
      ## I simplified this since I don't know what the function network is
      j <- i
      assign(output_name, j, envir = parent.frame())
    }
    
    node_attributes(mtcars)
    head(mtcars_network)
    ##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
    ## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
    ## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
    ## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
    ## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
    ## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
    ## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
    

    也就是说,我真的不认为有任何理由这样编写代码。通常,建议使用从函数返回输出的方法。

        2
  •  0
  •   JackStat    8 年前

    您可以使用 assign

    j <- network(i)
    assign(paste0(i,'network',sep = '_'), j)