jatin singh
jatin singh

Reputation: 123

If else loop error in R

I am trying to solve the question of compare triplets in R posted on hackerrank Although I have outlined the entitre steps still its not giving correct result not in hackerrank and in RStudio also . can anyone tell me

A reproducible example

m = data.frame(ints = as.integer())


m <- structure(rbind(m,c(5,6,7)), .Names = names(m))


m <- structure(rbind(m,c(3,6,10)), .Names = names(m))



names(m) = c("no1","no2","no3")


    enter## the output gives m as below 

`no1 no2 no3
1   5   6   7
2   3   6  10

## I need to compare the corresponding values in both rows

#if m[1,1] != m[2,1] then I need to store 1 in a vector or dataframe

#if m[1,2] != m[2,2] then I need to store 1 in a vector or dataframe

#if m[1,3] != m[2,3] then I need to store 1 in a vector or dataframe


#so We will get output as [1,1]

## defining a vector to store output as below

    g = c(0,0,0)

g = c(0,0,0)
> g
[1] 0 0 0
> g[1]
[1] 0

## so my answer is as  below 

if(m[1,1]== m[2,1]))
{
  print("nothing")
}
  else
   {
  (g[1] = 1)
   }


if((m[1,2]==m[2,2]))
{
  print("nothing")

}     
  else
   {

     (g[2] = 1)
    }


if((m[1,3]==m[2,3]))
 {
  print("nothing")

 }     
  else
   {

      (g[3] = 1)
   }      


g = data.frame()
g = c(0,0,0)

I get the following errors after every else

Error: unexpected 'else' in " else"

also g even takes value for middle value which it should never take

g
[1] 1 1 1

Can anyone explain what is going on why it is still placing 1 for middle value.

Upvotes: 1

Views: 254

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47310

In R an end of line marks the end of an instruction unless there are open parenthesis, open braces or an unfinished instruction, such as else to signify otherwise.

Try

if(m[1,1]== m[2,1]) {
  print("nothing")
} else
   {
  (g[1] = 1)
   }

Or shorter

if(m[1,1]== m[2,1])
  print("nothing") else
  g[1] = 1

Your problem in any case is better solved by:

g <- as.numeric(m[1,] != m[2,])
# [1] 1 0 1

Upvotes: 1

Related Questions