Anastasia Pupynina
Anastasia Pupynina

Reputation: 801

RegEx and stringr package

I am an R newbie and have troubles with my programming homework.

The input is a poem:

poem <- c(
  "Am Tag, an dem das L verschwand,", 
  "da war die Luft voll Klagen.",
  "Den Dichtern, ach, verschlug es glatt",
  "ihr Singen und ihr Sagen.",
  "Nun gut. Sie haben sich gefasst.",
  "Man sieht sie wieder schreiben.",
  "Jedoch:",
  "Solang das L nicht wiederkehrt,",
  "muß alles Flickwerk beiben.")

Now I need to extract all the capital letters and combine them into one word. I am doing this with the following code:

poem_cap <- str_extract_all(poem, "[[:upper:]]")

Then I unlist poem_cap:

one_word <- unlist(poem_cap)
one_word

The next logical step is to apply str_c:

one_word2 <- str_c(one_word, sep="")

But R keeps putting out separate letters! If I copy the output of one_word2, separate it with commas and apply str_c to the output, it works:

one_word2 <- str_c("A", "T", "L", "L", "K", "D", "D", "S", "S", "N", "S", "M", "J", "S", "L", "F", sep="")
one_word

Why does this happen? Is there a mistake I'm making? How do I transform one_word2 into something str_c I can work with?

Upvotes: 1

Views: 208

Answers (1)

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

Base R approach, you can simply use gsub in a one liner to keep only capital letters and paste them (with collapse, as @David Arenburg underlined):

paste(gsub('[^A-Z]','',poem), collapse='')
#[1] "ATLLKDDSSNSMJSLF"

Upvotes: 4

Related Questions