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

  • R Programming By Example
  • Omar Trejo Navarro
  • 194字
  • 2021-07-02 21:30:39

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
主站蜘蛛池模板: 龙江县| 萨迦县| 黄骅市| 中卫市| 抚顺市| 泰兴市| 怀仁县| 万载县| 丹巴县| 万源市| 小金县| 宜宾市| 普格县| 雅江县| 长兴县| 长岭县| 平陆县| 乐东| 光山县| 松溪县| 绿春县| 库车县| 双峰县| 休宁县| 长宁县| 石嘴山市| 博爱县| 民和| 江门市| 英吉沙县| 宁远县| 延庆县| 郸城县| 城市| 延津县| 富源县| 周至县| 阜南县| 丹巴县| 通江县| 辰溪县|