我看不懂你的代码?

R 函数编写入门

Richie Cotton

Data Evangelist at DataCamp

dplyr 动词

select() 选择列

filter() 过滤行

R 函数编写入门

函数名应包含动词

  • get(获取)
  • calculate(计算,或 calc)
  • run(运行)
  • process(处理)
  • import(导入)
  • clean(清洗)
  • tidy(整理)
  • draw(绘制)
R 函数编写入门

lm() 命名不佳

  • 缩写不自说明
  • 未包含动词
  • 线性模型有很多种

更好的名称是 run_linear_regression()

R 函数编写入门

可读性 vs. 可打性

  • 理解代码 >> 打字速度
R 函数编写入门

可读性 vs. 可打性

  • 理解代码 >> 打字速度
  • 代码编辑器有自动补全

DataCamp 自动补全截图

R 函数编写入门

可读性 vs. 可打性

  • 理解代码 >> 打字速度
  • 代码编辑器有自动补全
  • 可为常用函数设别名
h <- head
data(cats, package = "MASS")
h(cats)
  Sex Bwt Hwt
1   F 2.0 7.0
2   F 2.0 7.4
3   F 2.0 9.5
4   F 2.1 7.2
5   F 2.1 7.3
6   F 2.1 7.6
R 函数编写入门

lm() 的参数

args(lm)
function (formula, data, subset, weights, na.action, method = "qr", 
    model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE, 
    contrasts = NULL, offset, ...)
R 函数编写入门

参数类型

  • 数据参数:计算对象
  • 细节参数:计算方式
args(cor)
function (x, y = NULL, use = "everything", 
  method = c("pearson", "kendall", "spearman"))
R 函数编写入门

数据参数应先于细节参数

这不起作用

data %>%
  lm(formula)

因为 data 参数不是第一个。

R 函数编写入门

线性回归的改进函数

run_linear_regression <- function(data, formula) {
  lm(formula, data)
}
cats %>% 
  run_linear_regression(Hwt ~ Bet + Sex)
Call:
lm(formula = formula, data = data)

Coefficients:
(Intercept)          Bwt         SexM  
    -0.4150       4.0758      -0.0821
R 函数编写入门

让我们来练习!

R 函数编写入门

Preparing Video For Download...