问题描述
我是 R 新手,我的编程作业有问题.
I am an R newbie and have troubles with my programming homework.
输入是一首诗:
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:]]")
然后我取消列出poem_cap
:
one_word <- unlist(poem_cap)
one_word
下一个合乎逻辑的步骤是应用str_c
:
The next logical step is to apply str_c
:
one_word2 <- str_c(one_word, sep="")
但 R 一直在输出不同的字母!如果我复制 one_word2
的输出,用逗号分隔并将 str_c
应用到输出,它的工作原理:
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
为什么会这样?我犯了一个错误吗?如何将 one_word2
转换为我可以使用的 str_c
?
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?
推荐答案
Base R
方法,您可以简单地在一行中使用 gsub
只保留大写字母和粘贴它们(折叠,如@David Arenburg 下划线所示):
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"
这篇关于正则表达式和字符串包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!