- 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
- 高效能辦公必修課:Word圖文處理
- Practical Ansible 2
- 極簡AI入門:一本書讀懂人工智能思維與應(yīng)用
- 工業(yè)機器人入門實用教程(KUKA機器人)
- Visual FoxPro數(shù)據(jù)庫基礎(chǔ)及應(yīng)用
- 網(wǎng)絡(luò)安全技術(shù)及應(yīng)用
- 統(tǒng)計挖掘與機器學(xué)習(xí):大數(shù)據(jù)預(yù)測建模和分析技術(shù)(原書第3版)
- 格蠹匯編
- 網(wǎng)絡(luò)存儲·數(shù)據(jù)備份與還原
- 三菱FX/Q系列PLC工程實例詳解
- 電動汽車驅(qū)動與控制技術(shù)
- WPF專業(yè)編程指南
- JSP通用范例開發(fā)金典
- JSP網(wǎng)絡(luò)開發(fā)入門與實踐
- Cisco UCS Cookbook