首页 > 解决方案 > 循环根据 r 中的列表分配新对象名称

问题描述

我是阅读 xml 文件的新手,在将它们转换为列表后,我一直在尝试分配环境的新对象名称。

我读取了一个目录的 35 个文件,并用xmlParse, of XMLpackage 解析了它们。他们,我将它们转换成一个列表。

for(i in dir()){
  assign(i, xmlParse(i))}

for(i in ls()){
  assign(i, xmlToList(i))
}

rm(i)

所有文件都是这样的名称:

ls()

 [1] "en_product3_146.xml" "en_product3_147.xml" "en_product3_148.xml" "en_product3_149.xml"
 [5] "en_product3_150.xml" "en_product3_152.xml" "en_product3_156.xml" "en_product3_181.xml"
 [9] "en_product3_182.xml" "en_product3_183.xml" "en_product3_184.xml" "en_product3_185.xml"
[13] "en_product3_186.xml" "en_product3_187.xml" "en_product3_188.xml" "en_product3_189.xml"
[17] "en_product3_193.xml" "en_product3_194.xml" "en_product3_195.xml" "en_product3_196.xml"
[21] "en_product3_197.xml" "en_product3_198.xml" "en_product3_199.xml" "en_product3_200.xml"
[25] "en_product3_201.xml" "en_product3_202.xml" "en_product3_203.xml" "en_product3_204.xml"
[29] "en_product3_205.xml" "en_product3_209.xml" "en_product3_212.xml" "en_product3_216.xml"
[33] "en_product3_229.xml" "en_product3_231.xml" "en_product3_233.xml"

所有这些文件都具有相同的结构,我想将对象名称替换为这些列表的值。路径是:

    head(en_product3_150.xml$DisorderList$Disorder$ClassificationNodeList$ClassificationNode$ClassificationNodeChildList[5]$ClassificationNode$Disorder$Name$text)

[1] "Disorder of carbohydrate metabolism"

head(en_product3_147.xml$DisorderList$Disorder$ClassificationNodeList$ClassificationNode$ClassificationNodeChildList[5]$ClassificationNode$Disorder$Name$text)

[1] "Digestive tract malformation"

我在尝试assign使用新名称时遇到了一些麻烦,例如上面的代码,但我没有成功。

for(i in ls()){
assign(paste0(i,"$DisorderList$Disorder$ClassificationNodeList$ClassificationNode$ClassificationNodeChildList[5]$ClassificationNode$Disorder$Name$text"), i)}

我会很感激一些提示。提前致谢!

标签: rxmlassign

解决方案


您可能需要先使用get()来访问您环境中的对象,创建新对象的名称,然后使用assign()来分配。

rm(list = ls())

# put some things in the environment
x <- list(a = "hello", b = "world")
y <- list(a = "hola", b = "mundo")
z <- list(a = "bonjour", b = "monde")

# loop through environment objects; 
# use get() to access, and assign() to put back 
for (i in ls()) {
  temp <- get(i)
  new_name <- temp$a
  assign(new_name, temp)
  rm(i, temp) # removes object i, not the object whose name is stored in i
}

ls()

请注意,使用此代码,您将拥有两个名称不同但内容相同的对象。


推荐阅读