《R数据科学》笔记

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353