I'm new in reading xml files and I'm stuck trying to assign new objects names of the environment after convert them to a list.
I read 35 files of a directory and parsed them with xmlParse
, of XML
package. Them, I converted them into a list.
for(i in dir()){
assign(i, xmlParse(i))}
for(i in ls()){
assign(i, xmlToList(i))
}
rm(i)
all files are names like that:
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"
All these files have the same structure, and i want to replace the object name to a value of these list. The path is that:
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"
I'm having some trouble trying to assign
a new name, like the code above, but I not suceed.
for(i in ls()){
assign(paste0(i,"$DisorderList$Disorder$ClassificationNodeList$ClassificationNode$ClassificationNodeChildList[5]$ClassificationNode$Disorder$Name$text"), i)}
I would be very gratefull with some tips. Thanks in advance!
You may need to use get()
first to access the object in your environment, create the name of the new object, then use assign()
to 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()
Note that with this code, you'll have two objects with different names but same content.