Home > other >  Removing the last paragraph of a text in R
Removing the last paragraph of a text in R

Time:06-16

My Dataframe with around 200 entries is build as follows:

text <- as.data.frame("Lorem ipsum dolor sit amet, consetetur \n sadipscing elitr, sed diam nonumy eirmod tempor invidunt \n ut labore et dolore magna aliquyam erat, sed diam voluptua.\nAt vero eos et accusam et justo duo dolores et ea rebum.")
colnames(text) = "Lorem"

I am trying to delete the last paragraph of every entry. All of which are diffrent in text and length. My latest way of trying was to find a way to sub everything after the last linebreak.

text %>% mutate(Lorem = sub("\n{.,}$","", Lorem))

I have tried to find the right kind of RegEx but seem to be unsuccseful in doing so.

I have been able to create the opposite of what i need.

text %>% mutate(Lorem = sub(".*\n","", Lorem))

the result being: "At vero eos et accusam et justo duo dolores et ea rebum."

But also cant seem to find my way to the right negation for this term.

For this example the result would be: "Lorem ipsum dolor sit amet, consetetur \n sadipscing elitr, sed diam nonumy eirmod tempor invidunt \n ut labore et dolore magna aliquyam erat, sed diam voluptua."

CodePudding user response:

You could do:

text %>% mutate(Lorem = sub("\n[^\n] $", "", Lorem))
  • Related