Use function argument as name for new data frame in R

女生的网名这么多〃 提交于 2020-07-18 17:45:07

问题


this is very simple, but I have searched and failed to find a solution for this small problem.

I want to use the argument of a function as the name for a new data frame, for example:

assign.dataset<-function(dataname){
    x<-c(1,2,3)
    y<-c(3,4,5)
    dataname<<-rbind(x,y)
}

Then

assign.dataset(new.dataframe.name)

just creates a new dataset with the name dataname.

I have tried to use the paste and assign functions but with no success.

Many thanks


回答1:


You can do it like this...

assign.dataset<-function(dataname){
  x<-c(1,2,3)
  y<-c(3,4,5)
  assign(deparse(substitute(dataname)), rbind(x,y), envir=.GlobalEnv)
}

assign.dataset(new.dataframe.name)

new.dataframe.name
  [,1] [,2] [,3]
x    1    2    3
y    3    4    5



回答2:


Here is the rlang equivalent to @Andrew's answer:

library(rlang)

assign.dataset<-function(dataname){
  x<-c(1,2,3)
  y<-c(3,4,5)
  assign(quo_name(enquo(dataname)), rbind(x,y), envir=.GlobalEnv)
}

assign.dataset(test_df)

enquo captures the argument provided by the user and bundles it with the environment which the function was called into a quosure. quo_name then converts the quosure into a character.

However, I would advice against doing this instead of assigning the output of your function to an object. The following is how I would do it:

assign.dataset<-function(){
  x<-c(1,2,3)
  y<-c(3,4,5)
  rbind(x,y)
}

test_df = assign.dataset()

Result:

  [,1] [,2] [,3]
x    1    2    3
y    3    4    5


来源:https://stackoverflow.com/questions/47516904/use-function-argument-as-name-for-new-data-frame-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!