1
私の質問はこの1つの拡張で検索:各文に含まれる名前(逆ではない)
> sentences
[1] "Opposed as a reformer at Tübingen, he accepted a call to the University of Wittenberg by Martin Luther, recommended by his great-uncle Johann Reuchlin"
[2] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"
[3] " He studied the Scripture, especially of Paul, and Evangelical doctrine"
[4] " He was present at the disputation of Leipzig (1519) as a spectator, but participated by his comments."
[5] " Johann Eck having attacked his views, Melanchthon replied based on the authority of Scripture in his Defensio contra Johannem Eckium"
toMatch <- c("Martin Luther", "Paul", "Melanchthon")
提供の答えは、それぞれの名前と一致する文章を与える:
foo<-function(Match){c(Match,sentences[grep(Match,sentences)])}
> lapply(toMatch,foo)
[[1]]
[1] "Martin Luther"
[2] "Opposed as a reformer at Tübingen, he accepted a call to the University of Wittenberg by Martin Luther, recommended by his great-uncle Johann Reuchlin"
[3] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"
[[2]]
[1] "Paul"
[2] " He studied the Scripture, especially of Paul, and Evangelical doctrine"
[[3]]
[1] "Melanchthon"
[2] " Melanchthon became professor of the Greek language in Wittenberg at the age of 21 with the help of Martin Luther"
[3] " Johann Eck having attacked his views, Melanchthon replied based on the authority of Scripture in his Defensio contra Johannem Eckium"
lapply(toMatch,foo)
はtoMatch
要素とアプリのリストを与えます関数foo
にそれぞれgrep
(一致する文ベクトルの位置を返します)の文で一致するものを検索します:sentences[grep(Match,sentences)]
。他の方法で回避:
私の質問ではなくtoMatch
ベクトルの要素に一致するすべての文を返すので、どのように我々は、すべての文とベクトルを持つことができ、その後、各1(すなわち一致する名前を探し、あります、私はそれが少し混乱を知っている、出力)は、これを次のようになります。
[1] "Martin Luther"
[2] "Melanchthon","Martin Luther"
[3] "Paul"
[4] NA #Or maybe this row doesn't exists, it's the same for me
[5] "Melanchthon"
は、これは、すでに提供さ結果を変更することに行うことができるまたは多分これは、さまざまな機能やlapply(sentences,FUNCTION)
を使用して容易になるだろうか?
base R
から
regmatches/gregexpr
を使用し、(以前のように)NA
として0length
を持つlist
要素を置き換えることができますTh完璧で、ありがとう。一つのことは、 '' Paul ''がsetty [4]で4回出現した場合、あなたのコードの出力は' 'Paul' '、' 'Paul'''、' 'Paul'' 'Paul''です。それぞれの文章を一度だけ記入してください。 – Hoju@Hoju現在、すべての 'Paul'sを取得しますが、' unique'だけ必要な場合は 'lapply(lst、unique)'がそれを行います – akrun
'toMatch'という名前のベクトル関数のアプローチ 'foo <-function(Match){sentences [grep(Match、sentences)]}'を使うよりも、OR演算子の多くを連結する方が効率が悪いと思いますか?そのような関数を使って質問を解決する方法はありますか? 'grep(" \\ "、sentences)'のようなものを使うことができるので、文字列の代わりに単語だけを探すので、もっと速くなるかもしれないと思います。 –
Hoju