关于第一步(不是你正在做的事情有问题),你可以创建这样的名称:
temp <- combn(xvec, 2, FUN=paste, collapse=".")
这会生成所有组合,然后使用paste
它将组合折叠在一起。我使用.
, 因为*
在变量名中不是很好。您还可以检查?make.names
,一个使字符串适合用作名称的函数。
第二步
您可以使用assign
从存储在变量中的字符串创建变量。(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$NAME
现在,您可以使用、 或访问每个变量,myComb[[NAME]]
甚至可以attach(myComb)
将整个列表访问到您的环境中。
myCombs$edu.part
## [1] "This is the combination of edu and part"
我开始写一个小答案,但被带走了。希望这对你有帮助,
亚历克斯