简体   繁体   English

使用函数内部的向量作为参数

[英]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). 我使用一个名为mplusObject的函数而不是包含文件名作为参数,我希望能够使用此代码运行循环并让R自动输入文件名(请参阅代码末尾的VECTOR_1)。 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). 函数mplusObject(在MplusAutomation包中)有几个参数,包括一个用于保存模型生成的文件的文件名(在上面的代码末尾)。 Instead of the filename, I have now written VECTOR_1. 我现在写了VECTOR_1而不是文件名。

I would like to define the content of VECTOR_1 (VECTOR_1 <- "filename") outside the function. 我想在函数外定义VECTOR_1 (VECTOR_1 <- "filename")的内容。 Coming from Stata, I thought this would be easy (by using something similar to what Stata calls local macros). 来自Stata,我认为这很容易(通过使用类似于Stata所谓的本地宏的东西)。 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? 但是我没有成功用R.如何向R显示VECTOR_1是一个向量而不应该被视为实际的参数?

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: 并使用lapply将其循环以将所有输出保存在列表中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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