在R中创建n个变量的m向相互作用



我有七个变量,我想创建许多新变量,每个变量是七个变量的一个交互项。将会有双向到五向的互动。我打算分两步来做。

首先,创建变量名称的全m-way组合。其次,将名称转换为实际变量。我已经完成了第一步,但不知道如何做第二步。

第一步是:

xvec = c("white", "married", "inftype", "usecondom", "age", "edu", "part")
temp = t(combn(xvec, 2))
temp = paste(temp[,1], "*", temp[,2], sep="")

给出了名称的所有双向组合/交互。但是,如何将名称转换为实际变量呢?我曾经使用get()或eval(parse())做过类似的事情。但现在它们都不起作用了。

提前感谢!

关于第一步(不是说您正在做的事情有问题),您可以创建这样的名称:

temp <- combn(xvec, 2, FUN=paste, collapse=".")

这产生了所有的组合,然后使用paste,它将组合折叠在一起。我用.,因为*在变量名中不是很好。您还可以检查?make.names,该函数使字符串适合用作名称。

第二步您可以使用assign从存储在variable中的字符串创建变量。(get是当你有一个现有的变量的名称作为一个字符串,并希望访问它)

试试这样写:

for(nm in make.names(temp)) {
  assign(nm, "Put something more interesting here")
}

您可以使用ls()查看环境中的所有对象

ls()
## [1] "age.edu"           "age.part"          "edu.part"         
## [4] "inftype.age"       "inftype.edu"       "inftype.part"     
## [7] "inftype.usecondom" "married.age"       "married.edu"      
## [10] "married.inftype"   "married.part"      "married.usecondom"
## [13] "nm"                "temp"              "usecondom.age"    
## [16] "usecondom.edu"     "usecondom.part"    "white.age"        
## [19] "white.edu"         "white.inftype"     "white.married"    
## [22] "white.part"        "white.usecondom"   "xvec" 

现在你已经创建了很多变量。


作为一个注释,我想补充一下我可能会怎么做。

你可以使用一个列表(myCombs)来保存所有的对象,而不是用大量的对象填充你的环境。

myCombs <- combn(xvec, 2,simplify=FALSE, FUN = function(cmb) {
  res <- paste("This is the combination of", cmb[1], "and", cmb[2])
  res
})
##Add the names to the list items.
names(myCombs) <- combn(xvec, 2, FUN=paste, collapse=".")

我用这些术语构造了一个字符串。你可能想做一些更复杂的事情。如果您的环境中有xvec的项作为变量,您可以在这里使用get(cmb[1])get(cmb[1])访问它们。

现在您可以使用myCombs$NAMEmyComb[[NAME]]访问每个变量,或者您甚至可以将整个列表attach(myComb)发送到您的环境。

 myCombs$edu.part
 ## [1] "This is the combination of edu and part"

我开始写一个小的答案,但被冲昏了头脑。希望这对你有帮助,

亚历克斯

最新更新