我从 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_concat
为 text
列,然后交换默认 ,
与 .
一起出去. 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/