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

  • 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
主站蜘蛛池模板: 迁西县| 灵台县| 海兴县| 冀州市| 新乡县| 长丰县| 读书| 成都市| 涞源县| 随州市| 苗栗县| 无棣县| 镇巴县| 克什克腾旗| 滁州市| 陆丰市| 疏附县| 肇东市| 增城市| 雅江县| 察隅县| 宝坻区| 车致| 秦皇岛市| 松原市| 新昌县| 石城县| 洪泽县| 通化市| 长岛县| 东辽县| 湘西| 黎平县| 开封市| 睢宁县| 彭水| 阳新县| 乌拉特前旗| 南宫市| 广东省| 温泉县|