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

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
主站蜘蛛池模板: 阿拉尔市| 东阳市| 建阳市| 淮滨县| 上饶市| 永安市| 商城县| 运城市| 曲周县| 崇礼县| 台东市| 依安县| 古浪县| 南乐县| 罗甸县| 江陵县| 唐山市| 临洮县| 浦江县| 宜黄县| 云林县| 潼南县| 阿拉善右旗| 承德市| 双牌县| 台北县| 永城市| 古丈县| 凤山县| 龙门县| 伊宁县| 赤峰市| 吕梁市| 肃宁县| 建瓯市| 保靖县| 莱西市| 定南县| 五常市| 肇州县| 固安县|