官术网_书友最值得收藏!

Coercion

Finally, we will briefly mention what coercion is in R since it's a topic of confusion for newcomers. When you call a function with an argument of a different type than what was expected, R will try to coerce values so that the function will work, and this can introduce bugs if not handled correctly. R will follow a mechanism similar to what was used when creating vectors.

Strongly typed languages (like Java) will raise exceptions when the object passed to a function is of the wrong type, and will try not to convert the object to a compatible type. However, as we mentioned earlier, R was designed to work out of the box with a lot of unforeseen contexts, so coercion was introduced.

In the following example, we show that if we call our distance() function and pass logical vectors instead of numeric ones, R will coerce the logical vectors into numeric vectors, using TRUE as 1 and FALSE as 0, and proceed with the calculations. To avoid this issue in your own programs, you should coerce data types explicitly with the as.*() functions we mentioned before:

x <- c(1, 2, 3)
y <- c(TRUE, FALSE, TRUE)
distance(x, y)
#> [1] 8
主站蜘蛛池模板: 曲阜市| 蓬莱市| 玉田县| 从江县| 勃利县| 鹤壁市| 宣汉县| 清河县| 万年县| 达孜县| 黔西| 兴安盟| 明光市| 霍邱县| 宝兴县| 拉萨市| 晋州市| 东辽县| 太康县| 新邵县| 什邡市| 柳州市| 衡阳县| 信宜市| 梓潼县| 华安县| 东港市| 伊通| 苏尼特右旗| 天长市| 客服| 九龙城区| 南郑县| 南江县| 巢湖市| 寻甸| 屯昌县| 法库县| 永平县| 明光市| 宁强县|