2017-02-02 33 views
-3

我做了一個非常基本的循環,並且如果語句條件函數但每次將變量「words」中的每個第二個元素與向量輸入「t」匹配時,我想要完全刪除該匹配元素。R:從向量中刪除元素時出錯

matching <- function (t, words){ 

    for (i in 1:length(t)) { 
    if (t[i] == words[2]){ 
     t[i] <- NULL 
    } 

    } 
    t 

} 

但如果我輸入的東西像t <- c("Where", "is", "the", "money", "here") 並調用與匹配功能(T,C( 「是」, 「中」)),該函數休息。 「t [i]中的錯誤< - NULL:替換長度爲零」 如何解決此問題?我希望得到的輸出與

[1] "Where" "is" "money" "here" 

,基本上我想它對於任何輸入我投入到這個功能工作.. 此外,我想找到沒有使用像刪除特殊功能的方式()或類似的東西這..

編輯:沒有的grep,粘貼,GSUB,刪除等..無特殊R的功能和

+0

爲什麼'is'被包含在輸出?它應該刪除'is'和'''權利?也許像't [!grepl(paste(word,collapse =「|」),t)]或'grep(paste(word,collapse =「|」),t,invert = T,value = T) ? –

+0

你想刪除'文字'中的第二個元素嗎?應該「保持原樣」,只有「」應該被刪除? –

+0

是的,只有文字中的第二個元素。 「是」應該保持不變。 – oooooooooooooo

回答

0

這將這樣的伎倆:

t <- c("Where", "is", "the", "money", "here") 
word <- c("is", "the") 

matching <- function (t, words){ 
    # initialize vector 
    tmp <- c() 
    for (i in 1:length(t)) { 
     if (t[i] != words[2]){ 
     tmp <- c(tmp, t[i]) 
     } 

    } 
    return(tmp) 
} 
+0

謝謝..我沒有意識到我可以做到這一點,然後將其分配給一個全新的矢量。當我這次真的做了些什麼時,爲什麼我得到了低估...我不明白這一點.. – oooooooooooooo

+0

我不知道你的選票不對。我剛剛開始積極參與,但幫助中心的[投票部分](http://stackoverflow.com/help/privileges/vote-down)可能可以幫助您。 – ricoderks

0

假設你想從t去除word只有第二個元素,我們可以嘗試使用grep沿其invertvalue財產

grep(word[2], t, invert = TRUE, value = TRUE) 
#[1] "Where" "is" "money" "here" 

其中

t <- c("Where", "is", "the", "money", "here") 
word <- c("is", "the") 

這裏word是要由t刪除的話。 grepinvert屬性返回不匹配的值。


編輯:按照OP的評論應該使用沒有 '特殊' 功能。下面是繼續for

matching <- function (t, words){ 
    flag = FALSE 
    for (i in 1:length(t)) { 
    if (t[i] == words[2]){ 
     t[i] <- t[i+1] 
     flag = TRUE 
    } 
    if(flag) { 
     t[i] <- t[i+1] 
    } 
    } 
    t[-length(t)] 
} 

樣本輸出一試:

matching(t, word) 
#[1] "Where" "is" "money" "here" 
+0

我無法用其他方法解決這個問題嗎?我不允許使用grep,gsub,刪除或類似的東西... – oooooooooooooo

+0

如果我可以使用這些,我的意思是,我不會問這個問題是誠實的。,, – oooooooooooooo