= 和 == 有什么区别? [英] What is the difference between = and ==?

查看:65
本文介绍了= 和 == 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

=== 有什么区别?我发现双等号允许我的脚本运行而一个等号产生错误消息的情况.我什么时候应该使用 == 而不是 =?

What is the difference between = and ==? I have found cases where the double equal sign will allow my script to run while one equal sign produces an error message. When should I use == instead of =?

推荐答案

= 的含义取决于上下文.== 总是用于测试相等性.

It depends on context as to what = means. == is always for testing equality.

= 可以是

  1. 在大多数情况下用作<-(赋值运算符)的替代.

  1. in most cases used as a drop-in replacement for <-, the assignment operator.

> x = 10
> x
[1] 10

  • 用作键值对的分隔符,用于在函数调用中为参数赋值.

  • used as the separator for key-value pairs used to assign values to arguments in function calls.

    rnorm(n = 10, mean = 5, sd = 2)
    

  • 由于上面的 2.,= 不能在所有情况下用作 <- 的直接替代品.考虑

    Because of 2. above, = can't be used as a drop-in replacement for <- in all situations. Consider

    > rnorm(N <- 10, mean = 5, sd = 2)
     [1] 4.893132 4.572640 3.801045 3.646863 4.522483 4.881694 6.710255 6.314024
     [9] 2.268258 9.387091
    > rnorm(N = 10, mean = 5, sd = 2)
    Error in rnorm(N = 10, mean = 5, sd = 2) : unused argument (N = 10)
    > N
    [1] 10
    

    现在有些人会认为 rnorm(N <- 10, mean = 5, sd = 2) 编程很差,但它是有效的,您需要了解 之间的差异=<- 用于赋值.

    Now some would consider rnorm(N <- 10, mean = 5, sd = 2) poor programming, but it is valid and you need to be aware of the differences between = and <- for assignment.

    == 总是用于相等性测试:

    == is always used for equality testing:

    > set.seed(10)
    > logi <- sample(c(TRUE, FALSE), 10, replace = TRUE)
    > logi
     [1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE
    > logi == TRUE
     [1] FALSE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE
    > seq.int(1, 10) == 5L
     [1] FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE FALSE
    

    但是也要小心 == ,因为它实际上意味着完全等于并且在涉及浮点运算的计算机上您可能无法得到您期望的答案.例如,来自 ?'==':

    Do be careful with == too however, as it really means exactly equal to and on a computer where floating point operations are involved you may not get the answer you were expecting. For example, from ?'==':

    > x1 <- 0.5 - 0.3
    > x2 <- 0.3 - 0.1
    > x1 == x2                           # FALSE on most machines
    [1] FALSE
    > identical(all.equal(x1, x2), TRUE) # TRUE everywhere
    [1] TRUE
    

    where all.equal() 测试相等性,允许由于精度/浮点运算的损失而产生一些模糊性.

    where all.equal() tests for equality allowing for a little bit of fuzziness due to loss of precision/floating point operations.

    这篇关于= 和 == 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆