如何从 R 中的非结构化数据集中过滤出特定短语并将其放入新数据框中

How to filter out a particular phrase from a unstructured data set in R and put it in a new data frame

我正在清理大量非结构化数据,实际上是代码页。我需要从此代码中提取一个全部以

这是我在 .txt 文件中的示例数据。我需要查找术语 的新列中

</bi:data_source_alias>
    <bi:component name="ROOT" type="ABSOLUTE_LAYOUT_COMPONENT">
        <bi:component name="CHART_1" type="com_sap_ip_bi_VizFrame">
            <bi:property name="LEFT_MARGIN" value="31"/>`       <bi:property name="TOP_MARGIN" value="64"/>
<bi:component name="SCORECARD_1" type="com_sap_ip_bi_Scorecard">
            <bi:property name="LEFT_MARGIN" value="9"/>

这是我目前所做的。

  1. 将整个 .txt 文件读入名为 df1 的数据框中

  2. 然后我使用以下命令对 df1 应用过滤器

    comp_type <- df1 %>%
        filter(str_detect(str_to_lower(Value), "\<bi:component name="))
    
    comp_type <- df1[sapply(strsplit(df1$Value, "\s+"), 
       function(x) any(grepl("^<bi:component name=", tolower((x))))) ]
    

值是显示所有组件列表的字段名称。 Image showing data frame

但是我在执行上述命令时遇到错误。

Error in UseMethod("filter_") : no applicable method for 'filter_' applied to an object of class "c('matrix', 'logical')"

我已参考以下 link 寻求帮助,并参考了其他几个网站,但无法获得所需的输出。如果你能帮我找到正确的命令来过滤术语并将其放入新字段,那就太好了。

如果要向现有数据框 df 添加包含 type 描述的新列 component,其中包含 post 中给出的大字符串,那么这应该有效:

解决方案:

df$component <- str_extract_all(df$v1, '(?<=bi:component name="\w{1,100}" type=")[^"]+')

这利用了正后向 (?<=...) 以及 \w 不仅匹配字母而且匹配数字 下划线这一事实都涉及到bi:component name.

的值

结果:

df
v1
1 </bi:data_source_alias>\n    <bi:component name="ROOT" type="ABSOLUTE_LAYOUT_COMPONENT">\n        <bi:component name="CHART_1" type="com_sap_ip_bi_VizFrame">\n            <bi:property name="LEFT_MARGIN" value="31"/>`       <bi:property name="TOP_MARGIN" value="64"/>\n<bi:component name="SCORECARD_1" type="com_sap_ip_bi_Scorecard">\n            <bi:property name="LEFT_MARGIN" value="9"/>
                                                                   component
1 ABSOLUTE_LAYOUT_COMPONENT, com_sap_ip_bi_VizFrame, com_sap_ip_bi_Scorecard

数据:

df <- data.frame(
  v1 = '</bi:data_source_alias>
    <bi:component name="ROOT" type="ABSOLUTE_LAYOUT_COMPONENT">
        <bi:component name="CHART_1" type="com_sap_ip_bi_VizFrame">
            <bi:property name="LEFT_MARGIN" value="31"/>`       <bi:property name="TOP_MARGIN" value="64"/>
<bi:component name="SCORECARD_1" type="com_sap_ip_bi_Scorecard">
            <bi:property name="LEFT_MARGIN" value="9"/>'
)