简体   繁体   中英

Using a vector inside a function as argument

I use a function called mplusObject and rather than including a filename as an argument, I want to be able to run a loop with this code and let the filename be entered automatically by R (see VECTOR_1 towards the end of the code). This is a short and simplified version of the code:

mymodel <- mplusObject(
TITLE = "Some analysis;",
VARIABLE = "
  usevariables = x1 x2 x3 c_age c_agesq;",
MODEL = "
  att BY x1 x2 x3;
  att ON c_age c_agesq;",
SAVEDATA = "
  save = fscores; 
  file = VECTOR_1;",
  rdata = selectedgroup)

The function mplusObject (in the package MplusAutomation) has several arguments, including one where it gives a filename for saving data generated by the model (towards the end of the code above). Instead of the filename, I have now written VECTOR_1.

I would like to define the content of VECTOR_1 (VECTOR_1 <- "filename") outside the function. Coming from Stata, I thought this would be easy (by using something similar to what Stata calls local macros). But I don't succeed with R. How do I show R that VECTOR_1 is a vector and shouldn't be taken as the actual argument?

You can save your filepaths in a vector with

myvector <- c("filepath1", "filepath2", ...)

and loop over it with lapply to save all your outputs in a list:

mymodels <- lapply(myvector, function(x) mplusObject(all other fixed arguments, file = x))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM