美文网首页
《R数据科学》笔记

《R数据科学》笔记

作者: 琼脂糖 | 来源:发表于2018-10-16 16:52 被阅读35次

    1. Intro

    1.1. 有效的提问

    1. 包含三部分:需要的packages, data, code.
    2. 先更新包。比如tidyverse_updata()
    3. dput(mtcars)重新生成自己的数据。提供给别人重复。

    2. 数据可视化

    2.1. intro

    1. 模版
      image.png
    2. 例子
      image.png

    3. workflow

    3.1. 基础

    1. seq(1, 10, length.out = 5)
    2. 变量命名,建议用下划线间隔
      image.png

    4. dplyr

    4.1. filter条件过滤

    1. filter根据给定条件过滤部分行。只包含条件为TRUE的,去掉FALSE和NA的值。
    2. 如果要保留NA的值
      filter(df, is.na(x) | x > 1)

    4.2. arrange排序

    1. code
    arrange(flights, desc(dep_delay))
    
    1. NA排在最后

    4.3. select选择列

    1. code
    #选择year列到day列间所有
    select(flights, year:day)
    #去掉year和day间列
    select(flights, -(year:day))
    
    1. 有用的函数
      starts_with("abc")matches names that begin with “abc”.
      ends_with("xyz") matches names that end with “xyz”.
      contains("ijk") matches names that contain “ijk”.
      matches("(.)\\1") selects variables that match a regular expression. This one matches any variables that contain repeated characters. You’ll learn more about regular expressions in strings.
      num_range("x", 1:3) matches x1, x2 and x3.

    2. 重命名
      rename(flights, tail_num = tailnum)

    3. everything 可用于调整排序,将部分列移到最左边
      select(flights, time_hour, air_time, everything())

    4.4. mutate加入新变量

    1. 刚创建的变量就可以refer
      image.png
    1. 只保留新变量用transmute
      image.png
    1. 一些会用到的运算符
    • %/% (integer division) and %% (remainder)

    • lead(), lag(),可与group_by一起用 。x - lag(x)x != lag(x)

      image.png
    • cumsum(), cumprod(), cummin(), cummax(), cummean(). RcppRoll(滚动窗口计算)

    • min_rank()

      image.png
    • row_number(), dense_rank(), percent_rank(), cume_dist(), ntile()

    4.5. summarise分组统计

    1. 和group_by一起用

      image.png
    2. 关于na.rm,在mean计算时候先去掉NA值。这样避免了算出来结果都是NA。

    3. 建议在分组统计中,加一个count(n)或者non-missing值的count sum(!is.na(x))

      image.png
      飞机平均每日delay时间,统计count。
      image.png
    4. 为了更好的研究趋势,可以将最小的observations的那些组排除掉。即去掉sample size少的,避免小样本容量组导致的极端偏差。
      it’s often useful to filter out the groups with the smallest numbers of observations, so you can see more of the pattern and less of the extreme variation in the smallest groups.

      image.png
    5. RStudio的cmd+shift+p,可以重发送刚运行的code chunk到console。这样方便多次修改n值,看结果的变化。

    6. 有用的函数:

    • median
    • sd(x), interquartile range IQR(x), median absolute deviation mad(x)。后两者可用于找outliers。
    • min(x), quantile(x, 0.25)得到比25%的值大的一个值, max(x).
    • first(x), nth(x,2), last(x). x为vector,first(x)即x[1]
    1. 与filter一起用
      以日期为分组,按deptime排序,r得到排位,然后通过range得到每天的最大和最小(r为全部的排名,不是以天为单位)

      image.png
    2. n()返回组的大小, sum(!is.na(x))非NA值的数目, n_distinct(x)得到unique值的数目

    3. 关于count()
      指定weight variable。这里相当于计算每架飞机(tailnum为飞机编号)飞过的总里程数。

      image.png
    4. ungroup()取消group

    4.6. Group和mutate及filter

    1. 找出每组最差的members
      image.png
    2. 找出大于某个阈值的所有组
      image.png

    5. workflow

    1. cmd+shift+N 打开空的编辑器
      cmd+Enter 执行当前代码
      cmd+shift+S 执行所有代码
      cmd+shift+F10 重启RStudio

    6. Tibbles

    1. as_tibble()将简单的数据框转换成tibble

    2. tibble()创建一个tibble

    3. code

    df$x
    #> [1] 0.434 0.395 0.548 0.762 0.254
    df[["x"]]
    #> [1] 0.434 0.395 0.548 0.762 0.254
    
    # Extract by position
    df[[1]]
    #> [1] 0.434 0.395 0.548 0.762 0.254
    df %>% .$x
    #> [1] 0.434 0.395 0.548 0.762 0.254
    df %>% .[["x"]]
    #> [1] 0.434 0.395 0.548 0.762 0.254
    

    7. Data Import

    7.1. 读取数据

    1. 函数
    • read_csv() reads comma delimited files, read_csv2() reads semicolon separated files (common in countries where , is used as the decimal place), read_tsv() reads tab delimited files, and read_delim() reads in files with any delimiter.
    • read_fwf() reads fixed width files. You can specify fields either by their widths with fwf_widths() or their position with fwf_positions(). read_table() reads a common variation of fixed width files where columns are separated by white space.
    • read_log() reads Apache style log files. (But also check out webreadr which is built on top of read_log() and provides many more helpful tools.
    1. 参数
      read_csv(file, col_names = TRUE, col_types = NULL, locale = default_locale(), na = c("", "NA"), quoted_na = TRUE, quote = "\"", comment = "", trim_ws = TRUE, skip = 0, n_max = Inf, guess_max = min(1000, n_max), progress = show_progress())
      file,col_names,na,comment,skip,col_names(可指定)

    7.2. 写入数据

    1. 函数
    • write_csv, write_tsv
    • write_rds, read_rds
    • write_excel_csv
    1. 其他函数
    • haven reads SPSS, Stata, and SAS files.
    • readxl reads excel files (both .xls and .xlsx).
    • DBI, along with a database specific backend (e.g. RMySQL, RSQLite, RPostgreSQL etc) allows you to run SQL queries against a database and return a data frame.

    8. dplyr处理关系数据

    8.1. 合并连接

    8.1.1. 内连接

    image.png

    只匹配键相等的行(观测),即保留同时存在于两个表中的观测。不常用,因为容易丢失观测。

    8.1.2. 外连接

    1. 左连接:保留x中的所有观测
      右连接:保留y中的所有观测
      全连接:保留x和y中的所有观测

    2. image.png

    8.1.3. 参数by

    1. 连接两个表是通过一个单变量来实现,需要这个变量在两个表中具有同样的名字。by = "key"
    2. `by = c("a" = "b")可以匹配x表中的a变量和y表中的b变量。输出结果使用x表中的变量。

    9.4. 筛选连接

    1. semi_join(x,y)保留x表中与y表中的观测相匹配的所有观测
      anti_join(x,y)丢弃x表中与y表中的观测相匹配的所有观测
    2. 半连接:像合并连接一样连接两个表,但不添加新列,而是保留x表中那些可以配配y表的行
      image.png
      重要的是存在匹配,匹配到哪条观测无关紧要。这样半连接不会像合并连接那样造成重复的行。
      image.png
    3. 反连接:半连接的逆操作。可以用于诊断连接中的不匹配。

    9. stringr处理字符串

    9.1. 基础

    1. 推荐用双引号创建字符
    2. str_length 字符串长度
    3. str_c组合两个或多个字符
      _1539484158_885230944.png

    字符向量合并成字符串 ,间隔符号


    _1539484273_309769392.png
    1. str_sub(x,start,end)
      _1539484424_793811016.png

    利用赋值形式更改字符

    _1539484461_1413330748.png

    9.2. 正则表达式

    9.2.1. 基础

    1. str_viewstr_view_all,接受一个字符向量和一个正则表达式。

    2. 精确匹配

      _1539484707_533262169.png
    3. 匹配任意字符

      _1539484718_1088015452.png
    4. 反义需要\\

      _1539484734_452447559.png

    9.2.2. 字符类别

    1. \d匹配任意数字
      \s匹配任意空白字符(空格,制表符,换行符)
      [abc]匹配a或b或c
      [^abc]匹配abc外的任意字符

    2. _1539485108_46530086.png

    9.2.3. 重复

    1. ?: 0 or 1
      +: 1 or more
      *: 0 or more

    相关文章

      网友评论

          本文标题:《R数据科学》笔记

          本文链接:https://www.haomeiwen.com/subject/njbhzftx.html