Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中的If-else循环错误_R_Loops_If Statement_Dataframe_Vector - Fatal编程技术网

R中的If-else循环错误

R中的If-else循环错误,r,loops,if-statement,dataframe,vector,R,Loops,If Statement,Dataframe,Vector,我试图解决在hackerrank上发布的R中比较三胞胎的问题 虽然我已经概述了整个步骤,但在hackerrank和RStudio中也没有给出正确的结果。有人能告诉我吗 可复制的例子 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)) nam

我试图解决在hackerrank上发布的
R
中比较三胞胎的问题 虽然我已经概述了整个步骤,但在hackerrank和RStudio中也没有给出正确的结果。有人能告诉我吗

可复制的例子

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)

任何人都能解释为什么它仍然将1作为中间值。

R
中,行尾标记一条指令的结束,除非有开括号、大括号或未完成的指令,如
else
,表示其他指令

试一试

或更短

if(m[1,1]== m[2,1])
  print("nothing") else
  g[1] = 1
在任何情况下,您的问题都可以通过以下方式得到更好的解决:

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

g感谢@Moody\u mudscappper对它的精彩解释。
if(m[1,1]== m[2,1])
  print("nothing") else
  g[1] = 1
g <- as.numeric(m[1,] != m[2,])
# [1] 1 0 1