使用 R 根据 XML 中同一节点内另一个属性中的值编辑属性的现有值

Edit existing value of attribute based on value in another attribute within the same node in XML with R

我想解析以下 XML。重复的属性名称很难获得我想要的输出。

似乎解决这个问题的一个明显方法是改变属性分数的值。

      <linescore score="129">
        <quarter quarter="1" score="16"/>
        <quarter quarter="2" score="30"/>
        <quarter quarter="3" score="42"/>
        <quarter quarter="4" score="27"/>
        <quarter quarter="5" score="9"/>
        <quarter quarter="6" score="5"/>

你如何根据 quarter 的值更改 score 的值?例如:

      <linescore score="129">
        <quarter quarter="1" score="16_1"/>
        <quarter quarter="2" score="30_2"/>
        <quarter quarter="3" score="42_3"/>
        <quarter quarter="4" score="27_4"/>
        <quarter quarter="5" score="9_5"/>
        <quarter quarter="6" score="5_6"/>

我试过使用 xml_replace 但没有成功。

这是一种方法:

library(xml2)
library(purrr)
xml <- read_xml('
<linescore score="129">
<quarter quarter="1" score="16"/>
<quarter quarter="2" score="30"/>
<quarter quarter="3" score="42"/>
<quarter quarter="4" score="27"/>
<quarter quarter="5" score="9"/>
<quarter quarter="6" score="5"/>
</linescore>')
xml %>% 
  xml_find_all("/linescore/quarter") %>% 
  walk(~xml_set_attr(.x, "score", paste(xml_attrs(.x)[c("score", "quarter")], collapse ="_"))) 
xml  
# xml_document}
# <linescore score="129">
# [1] <quarter quarter="1" score="16_1"/>
# [2] <quarter quarter="2" score="30_2"/>
# [3] <quarter quarter="3" score="42_3"/>
# [4] <quarter quarter="4" score="27_4"/>
# [5] <quarter quarter="5" score="9_5"/>
# [6] <quarter quarter="6" score="5_6"/>