Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
502 views
in Technique[技术] by (71.8m points)

character - Load() function in R with an input

I am using R to create a function that allows me to load specific Rdata. So I have several different files, each containing a specific Rdata set. For instance, if I want to load the information about the northern line, I would write load(“TfL/Line/northern/Arrivals.Rdata")

And if I want circle line, I would write load(“TfL/Line/circle/Arrivals.Rdata")

The question is, can I write a function that takes the name of the tube line, say LineName,as an input, using the load function? I tried

Get_information<- function(LineName==NULL){
load(“TfL/Line/LineName/Arrivals.Rdata")}

This doesn’t work. Could someone help me deal with this? Thanks!

question from:https://stackoverflow.com/questions/65832900/load-function-in-r-with-an-input

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to pass 'LineName' as a variable. Currently you're just writing "LineName" as a string-literal.

There are a few functions which can do this:

Paste0

Paste0 combines character vectors (literals or objects) into a single string:

load(paste0(“TfL/Line/", LineName, "/Arrivals.Rdata"))

Glue

Glue is a CRAN package which functions in a similar way to paste0, but can be easier to write and read:

#install.packages("glue") #<- run if you don't have glue installed
require("glue") # attach the package so that we can use 'glue'
load(glue("TfL/Line/{LineName}/Arrivals.Rdata"))

If run either of those inside your function, it will work as intended.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...