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

How to use object name in paste?

我正在尝试创建一个用户定义的函数,该函数的一个输出是一个网络对象,该对象的名称与函数中使用的输入数据帧的名称类似。像这样。

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

想法是在 i 变量上添加“_network”,这意味着是一个数据帧。因此,如果我的原始数据帧是 foo_bar_data,我的输出将是:foo_bar_data_network.

你可以使用assign

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

可以通过deparse(substitute(argname))获取输入变量的名称。

func <- function(x){
  depsrse(substitute(x))
}

func(some_object)
## [1] "some_object"

我不完全确定你想如何使用输入的名称,所以我使用了类似于@JackStat

的答案的东西
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

也就是说,我真的看不出有任何理由像这样编写代码。通常,返回函数的输出是推荐的方式。