前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >70-R茶话会15-你的编程菜鸟路上缺失的一课

70-R茶话会15-你的编程菜鸟路上缺失的一课

作者头像
北野茶缸子
发布2021-12-17 11:02:41
3K0
发布2021-12-17 11:02:41
举报
文章被收录于专栏:北野茶缸子的专栏

参考:

  • Ten random useful things in R that you might not know about - KDnuggets[1]

前言

一个都是些非常有启发的建议。不谋而合的是,很多我之前都介绍过了。

这就是优秀者们的马太效应吗!

1-switch和case_when

在做数据分析时,常常遇到的一个场景是,1,2,3 需要转换成其对应的"a","b","c"。比如在对结果进行分类统计的时候。

这时候或许可以借助循环和switch 实现替换,教程在,[[17-R编程03-控制语句与函数]]:

代码语言:javascript
复制
> sapply(tmp, function(x){
+   switch(EXPR = x,
+          a = 1, 
+          b = 2, 
+          c = 3)
+ })
c b c c b c c c c a a a b b b b c b a a 
3 2 3 3 2 3 3 3 3 1 1 1 2 2 2 2 3 2 1 1 

但这样的循环编程语法是低效的,dplyr 提供了向量化的操作[[37-R茶话会07-高效的处理数据框的列]]:

代码语言:javascript
复制
> dplyr::case_when(
+   tmp %in% "a" ~ 1,
+   tmp %in% "b" ~ 2,
+   tmp %in% "c" ~ 3,
+   TRUE ~ 0
+ )
 [1] 3 2 3 3 2 3 3 3 3 1 1 1 2 2 2 2 3 2 1 1

2-R 的快捷键

我早就介绍过了:[[05-R工具指南04-俺的技巧与Rstudio的快捷键]]

3-通过设置系统变量保护脚本中的密码不外露

如果你的脚本中需要你的某些签名或密码,最好不要把他们放在脚本里,因为你的脚本可能会分享给其他人。

可以使用系统变量:

代码语言:javascript
复制
Sys.setenv(
  DSN = "database_name",
  UID = "User ID",
  PASS = "Password"
)

接着在脚本中使用这些键即可:

代码语言:javascript
复制
db <- DBI::dbConnect(
  drv = odbc::odbc(),
  dsn = Sys.getenv("DSN"),
  uid = Sys.getenv("UID"),
  pwd = Sys.getenv("PASS")
)

4-代码格式化问题

其实我已经介绍过[[41-R茶话会08-优秀的R使用者,优秀的代码习惯]],以及包:[[22-R茶话会03-美化代码]]

这一次来看看tidyverse 官方的包:Welcome | The tidyverse style guide[2]

网站也提供了相关tidyverse 团队的代码书写习惯。

5-学会在你的R 分享内容里使用变量

以Rmd 为例子: You can do this by defining parameters in the YAML header of your R Markdown document, and giving each parameter a value.

代码语言:javascript
复制
params:
  animal_name:
    value: Dog
    choices:
      - Dog
      - Cat
      - Rabbit
  years_of_study:
    input: slider
    min: 2000
    max: 2019
    step: 1
    round: 1
    sep: ''
    value: [2010, 2017]

Now you can write these variables into the R code in your document as paramsanimal_name and paramsyears_of_study. However, if you knit with parameters by selecting this option in RStudio’s Knit dropdown (or by using knit_with_parameters()), a lovely menu option appears for you to select your parameters before you knit the document. Awesome!

6-用 revealjs将Rmd 结果输出为html 幻灯

参见一个例子:hr_meetup_london/presentation.Rmd at master · keithmcnulty/hr_meetup_london (github.com)[3]

以及官方教程:rstudio/revealjs: R Markdown Format for reveal.js Presentations (github.com)[4]

例子如下:revealjs/simple.Rmd at main · rstudio/revealjs (github.com)[5]

结果以html 显示,感觉很棒:

我现在给别人作项目,直接交Rmd,和html 的输出,可以用这个包将html输出转成类似ppt 的效果。

7-shiny 相关

flexdashboard快速搭建shiny分析网页

flexdashboard 包提供了一个快速搭建shiny分析网页的可能。

ps:似乎shiny 的拓展分析页面模板非常多,这里我持谨慎太多。例子:Example projects • flexdashboard (rstudio.com)[6]

shiny 测试的两个好用函数:req and validate functions

  • The req() function allows you to prevent an action from occurring unless a another variable is present in the environment, but does so silently and without displaying an error. So you can make the display of UI elements conditional on previous actions.
代码语言:javascript
复制
output$go_button <- shiny::renderUI({

  # only display button if an animal input has been chosen

  shiny::req(input$animal)

  # display button
  
  shiny::actionButton("go",
                      paste("Conduct", input$animal, "analysis!")
  )
})
  • validate() checks before rendering an output and enables you to return a tailored error message should a certain condition not be fulfilled, for example if the user uploaded the wrong file:
代码语言:javascript
复制
# get csv input file

inFile <- input$file1
data <- inFile$datapath

# render table only if it is dogs

shiny::renderTable({
  # check that it is the dog file, not cats or rabbits
  shiny::validate(
    need("Dog Name" %in% colnames(data)),
    "Dog Name column not found - did you load the right file?"
  )

  data
})

关于更多介绍,参考:In R Shiny, when is an error really an error? | by Keith McNulty | Towards Data Science[7]

8-没事夸夸自己,装装逼

学习这么久,不如让R 包praise 夸夸你把。

代码语言:javascript
复制
Restarting R session...


If you think you can learn all of R, you are wrong. For the foreseeable future
you will not even be able to keep up with the new additions.
   -- Patrick Burns (Inferno-ish R)
      CambR User Group Meeting, Cambridge (May 2012)

[1] "You are lovely!"
[1] "You are outstanding!"
Hello Peng!
Welcome at Mon Dec  6 11:47:48 2021
We will use 3 cores for installing.

比如添加到启动环境里,见面就夸我,怪不好意思的,[[10-R工具指南09-自定义R的启动环境]]

花里胡哨的tag

Most people don’t take full advantage of the HTML tags available in R Shiny. There are 110 tags which offer shortcuts to various HTML formatting and other commands. Recently I built a shiny app that took a long time to perform a task. Knowing that the user would likely multitask while waiting for it to complete, I used tags$audio to have the app play a victory fanfare to alert the user when the task was complete.

参考资料

[1]Ten random useful things in R that you might not know about - KDnuggets: https://www.kdnuggets.com/2019/06/ten-useful-things-r.html

[2]Welcome | The tidyverse style guide: https://style.tidyverse.org/index.html

[3]hr_meetup_london/presentation.Rmd at master · keithmcnulty/hr_meetup_london (github.com): https://github.com/keithmcnulty/hr_meetup_london/blob/master/presentation.Rmd

[4]rstudio/revealjs: R Markdown Format for reveal.js Presentations (github.com): https://github.com/rstudio/revealjs

[5]revealjs/simple.Rmd at main · rstudio/revealjs (github.com): https://github.com/rstudio/revealjs/blob/main/examples/simple.Rmd

[6]Example projects • flexdashboard (rstudio.com): https://pkgs.rstudio.com/flexdashboard/articles/examples.html

[7]In R Shiny, when is an error really an error? | by Keith McNulty | Towards Data Science: https://towardsdatascience.com/in-r-shiny-when-is-an-error-really-an-error-702205ebb5d5

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-12-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 北野茶缸子 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 1-switch和case_when
  • 2-R 的快捷键
  • 3-通过设置系统变量保护脚本中的密码不外露
  • 4-代码格式化问题
  • 5-学会在你的R 分享内容里使用变量
  • 6-用 revealjs将Rmd 结果输出为html 幻灯
  • 7-shiny 相关
    • flexdashboard快速搭建shiny分析网页
      • shiny 测试的两个好用函数:req and validate functions
      • 8-没事夸夸自己,装装逼
        • 花里胡哨的tag
          • 参考资料
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档