简体   繁体   中英

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).

So my DF (sample) looks like this :

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 ?

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

Thank you

reproductible 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:

library(dplyr)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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