[英]How to use object name in paste?
I'm trying to create a user-defined function which has as one output a network object that is named similarly to the input dataframe used in the function. 我正在尝试创建一个用户定义的函数,该函数具有一个网络对象作为输出,该对象的名称与该函数中使用的输入数据帧的名称相似。 Something like this.
这样的事情。
node_attributes <- function(i){ #i is dataframe
j <- network(i)
##some other function stuff##
(i,'network',sep = '_')) <- j
}
The idea is to create add '_network' onto the i variable, which is meant to be a dataframe. 这个想法是在i变量上创建添加“ _network”,这意味着它是一个数据帧。 So if my orignial dataframe is foo_bar_data , my output would be: foo_bar_data_network .
因此,如果我的原始数据帧是foo_bar_data ,那么我的输出将是: foo_bar_data_network 。
you can use assign
您可以使用
assign
j <- network(i)
assign(paste0(i,'network',sep = '_'), j)
It is possible to get the name of input variables with deparse(substitute(argname))
. 可以使用
deparse(substitute(argname))
获得输入变量的名称。
func <- function(x){
depsrse(substitute(x))
}
func(some_object)
## [1] "some_object"
I am not completely sure how you want to use the name of the input, so I used something similar to the answer of @JackStat 我不确定您要如何使用输入的名称,因此我使用了类似于@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
That said I don't really see any reason to code like this. 就是说,我真的看不出有什么理由要编写这样的代码。 Normally, returning the output from the function is the recommended way.
通常,建议从函数返回输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.