Load a dataset into R with data() using a variable instead of the dataset name

99封情书 提交于 2019-11-30 18:12:03

Use the list argument. See ?data.

data(list=myvar)

You'll also need myvar to be a character string.

myvar <- "Titanic"

Note that myvar <- Titanic only worked (I think) because of the lazy loading of the Titanic data set. Most datasets in packages are loaded this way, but for other kinds of data sets, you'd still need the data command.

Use the variable as character. Otherwise you will be processing the contents of "Titanic" rather than its name. You may also need to use get in order to convert the character value to an object name.

myvar <- 'Titanic'

myfun <- function(mydataset) {
    data(list=mydataset)   
    str(get(mydataset))
}

myfun(myvar)

If the package has been loaded, you can use the get() function to assign the data set to a local variable:

data_object = get(myvar, asNamespace('<package_name>'))

or simply:

data_object = get(myvar)

Assign_Name <- read.csv(file.choose())

This line of code opens your local machine, just select the data-set you want to load it R environment

I am answering my own question, but I have found the solution at last. Quoting R help:

"Data sets are searched for in all the currently loaded packages, then in the ‘data’ directory (if any) of the current working directory."

Thus, all one has to do is write the dataset in a file and place it into a directory named "data" and located into the working directory.

> write.table(mydataset,file="dataset.csv",sep=",",quote=TRUE,row.names=FALSE)  # I intend to create a csv file, so I use 'sep=","' to separate the entries by a comma, 'quote=TRUE' to quote all the entries, and 'row.names=F to prevent the creation of an extra column containing the row names (which is the default behavior of write.table() )

# Now place the dataset into a "data" directory (either via R or via the operating system, doesn't make any difference):
> dir.create("data")  # create the directory
> file.rename(from="dataset.csv",to="data/dataset.csv")  # move the file

# Now we can finally load the dataset:
> data("mydataset")  # data(mydataset) works as well, but quoted is preferable - less risk of conflict with another object coincidentally named "mydataset" as well
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!