简体   繁体   English

R中的条件合并

[英]Conditional merging of row in R

I want to create individual transcripts in .txt files for each file of my data set which contains two colones LABEL (the word) and FILE (the file the word was said in). 我想为.txt文件中的数据集的每个文件创建单独的成绩单,其中包含两个冒号LABEL(单词)和FILE(单词在其中的文件)。

So my DF (sample) looks like this : 所以我的DF(样本)看起来像这样:

file        label
 bla_1       _
 bla_1       so
 bla_1       we
 bla_1     know
 bla_1     that
 bla_1     right 
 bla_2     my
 bla_2     mummy
 bla_2     said
 bla_2     so

I can easily paste everything together : 我可以轻松地将所有内容粘贴在一起:

text <-paste(unlist(sample), collapse =" ");text

Result is 结果是

"_ so we know that right my mummy said so"

But how could I insert an if statement that would generate individual text (and save them in separate files) according to the value of file ? 但是,我怎么能按值插入是否会产生单独的文本(并将其保存在单独的文件)语句file

bla_1     "_ so we know that right" 
bla_2     "my mummy said so"

Thank you 谢谢

reproductible DF : 生殖DF

sample <- data.frame(file=c(rep("bla_1",6),rep("bla_2",4)),label=c("_","so","we" ,"know" ,"that" ,"right" ,"my" ,"mummy" ,"said" ,"so"))

正如lukeA指出的那样,我只是忘记了在这种情况下可以正常工作的聚合函数。

aggregate(label~file, sample, paste, collapse = " ") 

Tidyverse approach: Tidyverse方法:

library(dplyr)

sample %>%
  group_by(file) %>% 
  summarise(paste(label, collapse = " "))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM