如何在R中创建导入函数中更改引用?

时间:2022-01-02 22:57:14

I tried to create a function that allows me to import file quickly, but I could not import it with the name I wanted.

我试图创建一个允许我快速导入文件的函数,但我无法使用我想要的名称导入它。

The code is as following:

代码如下:

g.import<- function(x) {
  x <<- read.csv(file.choose(), header=TRUE, sep=",")
  assign('x',x,envir=.GlobalEnv)
  return(head(x,3))
}
g.import(x=a)

I will get the imported file named x, but I want to be able to change the name...

我将获得名为x的导入文件,但我希望能够更改名称...

1 个解决方案

#1


1  

First, the <<- and assign() parts are redundant. If you want to call with a character value, you can use

首先,<< - 和assign()部分是多余的。如果要使用字符值调用,则可以使用

g.import<- function(x) {
  z <- read.csv(file.choose(), header=TRUE, sep=",")
  assign(x,z,envir=.GlobalEnv)
  return(head(z,3))
}
g.import(x="a")

to call with an unquoted symbol, you can use

用不带引号的符号调用,你可以使用

g.import<- function(x) {
  z <- read.csv(file.choose(), header=TRUE, sep=",")
  assign(deparse(substitute(x)),z,envir=.GlobalEnv)
  return(head(z,3))
}
g.import(x=a)

#1


1  

First, the <<- and assign() parts are redundant. If you want to call with a character value, you can use

首先,<< - 和assign()部分是多余的。如果要使用字符值调用,则可以使用

g.import<- function(x) {
  z <- read.csv(file.choose(), header=TRUE, sep=",")
  assign(x,z,envir=.GlobalEnv)
  return(head(z,3))
}
g.import(x="a")

to call with an unquoted symbol, you can use

用不带引号的符号调用,你可以使用

g.import<- function(x) {
  z <- read.csv(file.choose(), header=TRUE, sep=",")
  assign(deparse(substitute(x)),z,envir=.GlobalEnv)
  return(head(z,3))
}
g.import(x=a)