Advertisement

Statistics with R--Introduction to data--Week 1 Introduction to R and RStudio--Note

阅读量:

下载后,最先要做的是下载是哪个经常用的函数包

R Packages

  • statsr:用于教学课程中的数据文件和函数
  • dplyr:专门用于数据重塑
  • ggplot2:用于数据可视化

这门课里常用的是这三个

用install.packages & install_github 已经安装了

现在需要将其载入到Rstudio的工作环境中,用library

复制代码
 library(dplyr)

    
 library(ggplot2)
    
 library(statsr)

Data1:arbuthnot

复制代码
    data(arbuthnot)

data() 是载入数据的

复制代码
    arbuthnot

直接输入名字,后面会列出数据的详情

复制代码
    dim(arbuthnot)

为了更详细地了解相关信息,请通过调用dimension函数获取样本数据集的具体维度信息(数据集的大小)。

复制代码
    names(arbuthnot)

names命令 得出样本的所有变量名

复制代码
    arbuthnot$boys

The $ symbol serves to access the preceding data frame and locate the subsequent variable.

当结果显示时, 出现了vectors(作为变量)来代表一系列的数据. 这些方框展示了各个数据在其向量中的具体位置.

Taking into account 5218 corresponds to [1], which implies that 5218 is located at the first position in the vector. Suppose that [43] appears at the beginning of a line; this would signify that the initial number on such a line corresponds to the 43rd position in the vector.

数据可视化

复制代码
 ggplot(data = arbuthnot, aes(x = year, y = girls)) +

    
   geom_point()

有三个重点

  1. 第一个参数始终是数据集
  2. 然后我们从数据集中选择变量来分配到绘图的美学元素上(例如x轴和y轴)。
  3. 最后一步是添加一个分隔符(例如使用+号),指定绘图中的几何形状对象。由于我们想要散点图,默认情况下我们会使用geom_point(对于折线图则使用geom_line)。

ggplot函数具有多种用途。您可参考官方文档以获取更多细节。目前尚未有机会深入学习该库的具体功能与应用方法;但希望以后有机会再详细研究它。

计算器作用

复制代码
 5218 + 4683

    
 arbuthnot$boys + arbuthnot$girls

给数据框加一个新变量

复制代码
 arbuthnot <- arbuthnot %>%

    
   mutate(total = boys + girls)

被称为管道函数(piping operator)的操作符:它负责处理当前行的输出,并将其向前传递到后续行的代码中。

A note on piping: It is worth noting that we can interpret these three lines of code as follows:

Import the arbuthnot dataset into a data frame named Arbuthnot. Use a mutate function to compute a new variable named total, which represents the summation of variables boys and girls. Reassign this augmented dataset to an object named Arbuthnot, effectively replacing its contents with those of Arbuthnot plus its updated metrics.

设置了新变量怎么更新?names()可以更新变量名

复制代码
 arbuthnot <- arbuthnot %>%

    
   mutate(more_boys = boys > girls)

还可以加逻辑变量,如果表达式为真,显示TRUE,反之FLASE

Dataset 2: Present birth records

范围 :如何快速知道都有哪些年包括在数据框里了?

复制代码
    range(present$year)

先显示present数据中所有的年份,再求范围,显示的结果如下

排序:哪一年的男生最多?arrange()函数

复制代码
     arrange(present, desc(total))
  1. 第一个参数被称为dataset
  2. desc:descending order: 即, 按照total字段对present中的数据进行降序排列。

升序是______我没找到,marked 。

Resources for learning R and working in RStudio

好多啊,来不及看,存着

  • Data wrangling cheatsheet

http://www.rstudio.com/wp-content/uploads/2015/02/data-wrangling-cheatsheet.pdf

  • Data visualization cheatsheet

http://www.rstudio.com/wp-content/uploads/2015/12/ggplot2-cheatsheet-2.0.pdf

  • R Markdown

http://www.rstudio.com/wp-content/uploads/2016/03/rmarkdown-cheatsheet-2.0.pdf

  • 免费的R,Python练习网站,有视频课程听

https://www.datacamp.com/courses

全部评论 (0)

还没有任何评论哟~