Multiple conditions in if statements in R

Rohan Singhal picture Rohan Singhal · Feb 8, 2017 · Viewed 11.2k times · Source

I am trying to cut down a list of gene names that I have been given. I'm trying to eliminate any repetitive names that may be present but I keep getting an error when running my code:

counter=0
i=0
j=0
geneNamesRevised=array(dim=length(geneNames))
for (i in 0:length(geneNamesRevised))
  geneNamesRevised[i]=""
geneNamesRevised
for (i in 1:length(geneNames))
  for (j in 1:length(geneNamesRevised))
    if (geneNames[i]==geneNamesRevised[j])
    {
      break
    }
    else if ((j==length(geneNamesRevised)-1) &&
             (geneNames[i]!=geneNamesRevised[j]))
    {
      geneNamesRevised[counter]=geneNames[i]
      counter++
    }

The error message is a repetitive string of :

the condition has length > 1 and only the first element will be usedthe condition has length > 1 and only the first element will be usedthe condition has length > 1 and only the first element will be used

and this error message is for the last "else if" statement that has the '&&'.

Thank you!

Answer

IRTFM picture IRTFM · Feb 8, 2017

Why not just

geneNamesRevised <- unique( geneNames )

... which returns a shortened list. There is also a duplicated function that can be used to remove duplicates when negated.