我正在嘗試編寫一個函數,它將一個字符串作爲參數並在Pig Latin中打印該字符串。 (在PigLatin中,你將單詞的第一個字母移到末尾,然後添加「ay」,例如,「這很有趣」 - >「histay asway unfay」)。我剛剛開始在R,所以我只是設法做的是如何編寫生成豬拉丁語的函數R
function(x){
x<-c() str_sub(x, 2, -1)
....
}
但我真的不知道如何將第一個字母移到詞尾並添加ay。任何提示將非常感謝!
我正在嘗試編寫一個函數,它將一個字符串作爲參數並在Pig Latin中打印該字符串。 (在PigLatin中,你將單詞的第一個字母移到末尾,然後添加「ay」,例如,「這很有趣」 - >「histay asway unfay」)。我剛剛開始在R,所以我只是設法做的是如何編寫生成豬拉丁語的函數R
function(x){
x<-c() str_sub(x, 2, -1)
....
}
但我真的不知道如何將第一個字母移到詞尾並添加ay。任何提示將非常感謝!
使用基本R功能的一種方法可能是使用strsplit
和paste
的組合。我們可以創建作用於一個字
f_one = function(word){
letters = strsplit(word,"")[[1]]
paste(c(letters[-1],letters[1],"ay"),collapse = "")
}
f_one("this")
## [1] "histay"
其拆分成單獨的字母,然後使用粘貼貼的第一個字母到最後,然後添加「AY」的功能。
然後,我們可以用它作用於多個單詞串第二功能,分割字符串爲單個單詞,該功能適用於每一個單詞和粘貼的結果一起回來
f_multiple= function(words){
individual = strsplit(words," ")[[1]]
paste(sapply(individual,f_one), collapse = " ")
}
f_multiple("this was fun")
## [1] "histay asway unfay"
它使用與第一個功能相同的邏輯,但在空間上分割以提供單個單詞。要做到這一點
一種方法是使用paste0
聯接三個字符串:
#The first character of string x
substr(x,1,1)
#All characters of x except the first
substr(x,2,nchar(a))
# And the string "ay"
pig_latin_x = paste0(substr(x,2,nchar(a)), substr(x,1,1), "ay")
這將在一個字,而不是短語工作。首先用短語將他們分開。 jamieRowen的答案向您展示瞭如何實現這一目標。
使用一個正則表達式:
pl = function(x) {
x = unlist(strsplit(x, split=" "))
paste(gsub("(.)(.*)", "\\2\\1ay", x), collapse=" ")
}
pl = Vectorize(pl)
a = c("this was fun", "What is this in pig Latin")
pl(a)
this was fun What is this in pig Latin "histay asway unfay" "hatWay siay histay niay igpay atinLay"
我喜歡'pl'在單個函數中同時使用單個單詞和句子。儘管我懷疑我可以在我的答案中使用Vectorize來獲得相同的結果,但Cake上的錦上添花正在使用'Vectorize'。無論如何,我認爲「pl」是個很好的答案,所以+1。 – jamieRowen
'GSUB( 「(\\ w)的(\\ W +)」, 「\\ 2 \\ 1AY」,一)' – user20650