json - R:将特定行转换为列

标签 json r dplyr tidyr tidyverse

我从 json 文件导入了相当困惑的数据,它看起来像这样:

raw_df <- data.frame(text = c(paste0('text', 1:3), '---------- OUTCOME LINE ----------', paste0('text', 4:6), '---------- OUTCOME LINE ----------'),
                              demand = c('cat1', rep('', 2), 'info', 'cat2', rep('', 2), 'info2')
                     )



raw_df
                                text demand
1                              text1   cat1
2                              text2       
3                              text3       
4 ---------- OUTCOME LINE ----------   info
5                              text4   cat2
6                              text5       
7                              text6       
8 ---------- OUTCOME LINE ----------  info2

(顺便说一句,---------- OUTCOME LINE ---------- 是我在 text 列中的实际字符串)

我想整理一下,使其具有以下格式:
final_df
                  text demand outcome
1 text1. text2. text3.   cat1   info1
2 text4. text5. text6.   cat2   info2

什么是最快和最有效的方法来做到这一点?感谢您的提示。

最佳答案

一个 dplyr & tidyr解决方案:

raw_df %>% 
    mutate(outcome = demand,
           demand = replace(demand, demand == '', NA),
           outcome = replace(outcome, outcome == '', NA),
           outcome = gsub("^cat\\d+", NA, outcome)) %>% 
    fill(demand) %>% 
    fill(outcome, .direction = "up") %>% 
    filter(!grepl("-----", text)) %>%
    group_by(demand, outcome) %>% 
    summarize(text = gsub(",", "\\.", toString(text))) %>% 
    select(text, everything())
  • 修复文本以根据需要显示,将空白替换为 NA s,并准备结果列。
  • fill demand默认向下方向的列,向上方向的结果列。
  • filter----- OUTCOME LINE ------基于它的连字符。
  • 生成 group_concattext列,然后交换默认 ,. 一起出去.
  • select将列转换为所需的序列。

  • # A tibble: 2 x 3
    # Groups:   demand [2]
                     text demand outcome
                    <chr> <fctr>   <chr>
    1 text1. text2. text3   cat1    info
    2 text4. text5. text6   cat2   info2
    

    关于json - R:将特定行转换为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47262680/

    相关文章:

    r - R中按组计算多列的出现次数

    json - 使用 XPages 从托管 bean 获取数据

    javascript - 如何从 json 文件中获取最高 3 个值

    c++ - 尝试在 SET_VECTOR_ELT 中设置索引 0/0

    regex - 单词/字符的选择性正则表达式

    r - 如果一组行不包含特定单词,则过滤 dplyr 链中的行

    JSON 只解析为动态类型,而不是 Map

    json - 从ElasticSearch中的结果文档中排除字段

    r - 如何将 dplyr::tbl 连接编码更改为 utf8?

    r - Dplyr - 错误 : column '' has unsupported type