r xml合并列出函数中的元素,在函数内部时返回错误
我是r xml合并列出函数中的元素,在函数内部时返回错误,xml,r,list,function,merge,Xml,R,List,Function,Merge,我是R新手。在R中,我试图从XML节点的各个级别提取一些数据,并将其放入一个数据帧中 我想出的代码是这样的: src <- sapply(node[[1]][1:5], function(x) # extract data from first 5 sub-sub-nodes of 1st sub-node (example) { names <- xpathSApply(x, "choice", xmlGetAttr, "name") # return list
R
新手。在R
中,我试图从XML节点的各个级别提取一些数据,并将其放入一个数据帧中
我想出的代码是这样的:
src <- sapply(node[[1]][1:5], function(x) # extract data from first 5 sub-sub-nodes of 1st sub-node (example)
{
names <- xpathSApply(x, "choice", xmlGetAttr, "name") # return list of vectors
ids <- xpathSApply(x, "choice", xmlGetAttr, "id") # return list of vectors
names2 <- xpathSApply(x, ".", xmlGetAttr, "name") # return list of vectors
# merge lists together
final_list <- mapply(rbind, names, ids, names2)
# merge elements of final_list into data frame
df <- do.call(cbind.data.frame, final_list)
# -> returns error, doesn't work!!
}
)
df <- do.call(cbind.data.frame, src)
# works fine outside function
mapply
始终简化,因此不太可能生成列表作为输出。您可以尝试使用Map
,这不会简化。如果没有一个可复制的示例,就很难判断可能的错误。添加了xml代码以提供可复制的示例
<a name="node" >
<b>
<c name="subnode1" >
<choice name="1" id="125096778" />
<choice name="2" id="125096782" />
<choice name="3" id="125096786" />
</c>
<c name="subnode2" >
<choice name="1" id="125097062" />
<choice name="2" id="125097083" />
<choice name="3" id="125096990" />
<choice name="4" id="125097065" />
<choice name="5" id="125096984" />
</c>
<c name="subnode3” >
<choice name="1" id="125097219" />
<choice name="2" id="125097227" />
<choice name="3" id="125097231" />
<choice name="4" id="125097235" />
<choice name="5" id="125097243" />
<choice name="6" id="125097215" />
<choice name="7" id="125097239" />
<choice name="8" id="125097223" />
<choice name="9" id="125097247" />
</c>
<c name="subnode4" >
<choice name="1" id="125097251" />
<choice name="2" id="125097259" />
<choice name="3" id="125097255" />
</c>
<c name="subnode5" >
<choice name="1" id="125097303" />
<choice name="2" id="125097306" />
<choice name="3" id="125097309" />
</c>
</b>
</a>