第 52 章 懒人系列

R社区上很多大神,贡献了很多非常优秀的工具,节省了我们的时间,也给我们的生活增添了无限乐趣。我平时逛github的时候时整理一些,现在分享出来供像我一样的懒人用,因此本文档叫“懒人系列”。欢迎大家补充。

52.1 列名太乱了

library(tidyverse)
library(janitor)
## install.packages("janitor")
## https://github.com/sfirke/janitor
fake_raw <- tibble::tribble(
  ~id, ~`count/num`, ~W.t, ~Case, ~`time--d`, ~`%percent`,
  1L, "china", 3L, "w", 5L, 25L,
  2L, "us", 4L, "f", 6L, 34L,
  3L, "india", 5L, "q", 8L, 78L
)
fake_raw
## # A tibble: 3 x 6
##      id `count/num`   W.t Case  `time--d` `%percent`
##   <int> <chr>       <int> <chr>     <int>      <int>
## 1     1 china           3 w             5         25
## 2     2 us              4 f             6         34
## 3     3 india           5 q             8         78
fake_raw %>% janitor::clean_names()
## # A tibble: 3 x 6
##      id count_num   w_t case  time_d percent_percent
##   <int> <chr>     <int> <chr>  <int>           <int>
## 1     1 china         3 w          5              25
## 2     2 us            4 f          6              34
## 3     3 india         5 q          8              78

52.2 比count()更懂我的心

mtcars %>%
  count(cyl)
## # A tibble: 3 x 2
##     cyl     n
##   <dbl> <int>
## 1     4    11
## 2     6     7
## 3     8    14
mtcars %>%
  janitor::tabyl(cyl)
##  cyl  n percent
##    4 11  0.3438
##    6  7  0.2188
##    8 14  0.4375

52.3 比distinct()更知我心

df <- tribble(
  ~id, ~date, ~store_id, ~sales,
  1, "2020-03-01", 1, 100,
  2, "2020-03-01", 2, 100,
  3, "2020-03-01", 3, 150,
  4, "2020-03-02", 1, 110,
  5, "2020-03-02", 3, 101
)

df %>%
  janitor::get_dupes(store_id)
## # A tibble: 4 x 5
##   store_id dupe_count    id date       sales
##      <dbl>      <int> <dbl> <chr>      <dbl>
## 1        1          2     1 2020-03-01   100
## 2        1          2     4 2020-03-02   110
## 3        3          2     3 2020-03-01   150
## 4        3          2     5 2020-03-02   101
df %>%
  janitor::get_dupes(date)
## # A tibble: 5 x 5
##   date       dupe_count    id store_id sales
##   <chr>           <int> <dbl>    <dbl> <dbl>
## 1 2020-03-01          3     1        1   100
## 2 2020-03-01          3     2        2   100
## 3 2020-03-01          3     3        3   150
## 4 2020-03-02          2     4        1   110
## 5 2020-03-02          2     5        3   101

52.4 代码太乱了,谁帮我整理下

## install.packages("styler")

安装后,然后这两个地方点两下,就发现你的代码整齐很多了。或者直接输入

styler:::style_active_file()

52.5 谁帮我敲模型的公式

library(equatiomatic)
## https://github.com/datalorax/equatiomatic
mod1 <- lm(mpg ~ cyl + disp, mtcars)
extract_eq(mod1)

\[ \operatorname{mpg} = \alpha + \beta_{1}(\operatorname{cyl}) + \beta_{2}(\operatorname{disp}) + \epsilon \]

extract_eq(mod1, use_coefs = TRUE)

\[ \operatorname{mpg} = 34.66 - 1.59(\operatorname{cyl}) - 0.02(\operatorname{disp}) + \epsilon \]

52.6 模型有了,不知道怎么写论文?

library(report)
## https://github.com/easystats/report
model <- lm(Sepal.Length ~ Species, data = iris)
report(model)

We fitted a linear model (estimated using OLS) to predict Sepal.Length with Species (formula = Sepal.Length ~ Species). Standardized parameters were obtained by fitting the model on a standardized version of the dataset. Effect sizes were labelled following Cohen’s (1988) recommendations.

The model explains a significant and substantial proportion of variance (R2 = 0.62, F(2, 147) = 119.26, p < .001, adj. R2 = 0.61). The model’s intercept, corresponding to Sepal.Length = 0 and Species = setosa, is at 5.01 (SE = 0.07, 95% CI [4.86, 5.15], p < .001). Within this model:

  • The effect of Species [versicolor] is positive and can be considered as large and significant (beta = 0.93, SE = 0.10, 95% CI [0.73, 1.13], std. beta = 1.12, p < .001).
  • The effect of Species [virginica] is positive and can be considered as large and significant (beta = 1.58, SE = 0.10, 95% CI [1.38, 1.79], std. beta = 1.91, p < .001).

52.7 模型评估一步到位

library(performance)

model <- lm(mpg ~ wt * cyl + gear, data = mtcars)
performance::check_model(model)

52.8 统计表格不用愁

library(gtsummary)
## https://github.com/ddsjoberg/gtsummary


gtsummary::trial %>%
  dplyr::select(trt, age, grade, response) %>%
  gtsummary::tbl_summary(
    by = trt,
    missing = "no"
  ) %>%
  gtsummary::add_p() %>%
  gtsummary::add_overall() %>%
  gtsummary::add_n() %>%
  gtsummary::bold_labels()

直接复制到论文即可

t1 <-
  glm(response ~ trt + age + grade, trial, family = binomial) %>%
  gtsummary::tbl_regression(exponentiate = TRUE)

t2 <-
  survival::coxph(survival::Surv(ttdeath, death) ~ trt + grade + age, trial) %>%
  gtsummary::tbl_regression(exponentiate = TRUE)



gtsummary::tbl_merge(
  tbls = list(t1, t2),
  tab_spanner = c("**Tumor Response**", "**Time to Death**")
)

52.9 统计结果写图上

library(ggplot2)
library(statsExpressions)
# https://github.com/IndrajeetPatil/statsExpressions


ggplot(mtcars, aes(x = mpg, y = wt)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(
    title = "Spearman's rank correlation coefficient",
    subtitle = expr_corr_test(mtcars, mpg, wt, type = "nonparametric")
  )

52.10 正则表达式太南了

library(inferregex)
## remotes::install_github("daranzolin/inferregex")
s <- "abcd-9999-ab9"
infer_regex(s)$regex
## [1] "^[a-z]{4}-\\d{4}-[a-z]{2}\\d$"

有了它,妈妈再也不担心我的正则表达式了

52.11 颜控怎么配色?

library(ggthemr) ## devtools::install_github('cttobin/ggthemr')
ggthemr("dust")
mtcars %>%
  mutate(cyl = factor(cyl)) %>%
  ggplot(aes(x = mpg, fill = cyl, colour = cyl)) +
  geom_density(alpha = 0.75) +
  labs(fill = "Cylinders", colour = "Cylinders", x = "MPG", y = "Density") +
  legend_top()

用完别忘了

ggthemr_reset()

52.12 画图颜色好看不

scales也是大神的作品,功能多多

## https://github.com/r-lib/scales
library(scales)

show_col(viridis_pal()(10))

不推荐个人配色,因为我们不专业。直接用专业的配色网站 colorbrewer

先看看颜色,再选择

52.13 宏包太多

library(pacman)
## p_load(lattice, foreign, boot, rpart)

唉,这个library()都要偷懒,真服了你们了

52.14 犹抱琵琶半遮面

## https://github.com/EmilHvitfeldt/gganonymize
library(ggplot2)
library(gganonymize)

ggg <-
  ggplot(mtcars, aes(as.factor(cyl))) +
  geom_bar() +
  labs(
    title = "Test title",
    subtitle = "Test subtitle, this one have a lot lot lot lot lot more text then the rest",
    caption = "Test caption",
    tag = 1
  ) +
  facet_wrap(~vs)

gganonomize(ggg)

你可以看我的图,但就不想告诉你图什么意思,因为我加密了

52.15 整理Rmarkdown

# remotes::install_github("tjmahr/WrapRmd")
# remotes::install_github("fkeck/quickview")
# remotes::install_github("mwip/beautifyR")

52.16 如何有效的提问

直接看官方网站,这里不举例了

## install.packages("reprex")
## https://reprex.tidyverse.org/

52.17 程序结束后记得提醒我

## beepr::beep(sound = "mario")

你听到了声音吗?

52.18 多张图摆放

library(patchwork)
p1 <- ggplot(mtcars) +
  geom_point(aes(mpg, disp))
p2 <- ggplot(mtcars) +
  geom_boxplot(aes(gear, disp, group = gear))
p3 <- ggplot(mtcars) +
  geom_smooth(aes(disp, qsec))
p1 + p2 + p3

52.19 缺失值处理

library(naniar)
## https://github.com/njtierney/naniar

airquality %>%
  group_by(Month) %>%
  naniar::miss_var_summary()
## # A tibble: 25 x 4
## # Groups:   Month [5]
##    Month variable n_miss pct_miss
##    <int> <chr>     <int>    <dbl>
##  1     5 Ozone         5     16.1
##  2     5 Solar.R       4     12.9
##  3     5 Wind          0      0  
##  4     5 Temp          0      0  
##  5     5 Day           0      0  
##  6     6 Ozone        21     70  
##  7     6 Solar.R       0      0  
##  8     6 Wind          0      0  
##  9     6 Temp          0      0  
## 10     6 Day           0      0  
## # ... with 15 more rows

52.20 看看数据什么情况

library(visdat)

vis_dat(airquality)

52.21 管道都不想

管道都不想写, 写代码还有美感?

## library(nakepipe)

52.22 各种插件,任君选取

## https://github.com/daattali/addinslist