oooooooooooooo oooooooooooooo - 4 years ago 64
R Question

R: Error when deleting an element from a vector

I made a very basic for loop and if statement condition function but every time I match every 2nd element in the variable "words" to the vector input "t", I want to completely remove that matching element out.

matching <- function (t, words){

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

}
t

}


But if I input stuff like
t <- c("Where", "is", "the", "money", "here")

and call that function with matching(t, c("is", "the")), the function breaks.
"Error in t[i] <- NULL : replacement has length zero"
How do I fix this problem? I would want to get the output with

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


and basically I want it to work for ANY input I put into this function..
Also I want to find ways without using special functions like remove() or anything like that..

EDIT: No grep, paste, gsub, remove etc... NO SPECIAL R FUNCTIONS

Answer Source

This will do the trick:

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)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download