Tidyverse - TreetoForest/LearningNotes GitHub Wiki
Tidyverse
数据读取
library(tidyverse)
reader 支持 7 中文本格式,但是常用的读取命令主要有如下三个
read_csv()
: comma separated (CSV) files
read_tsv()
: tab separated files
read_delim()
: general delimited files
read_table()
: tabular files where colums are separated by white-space.
read_*(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())
数据整理 tidy
所谓 tidy 的含义其实就是**每一列是一个变量 (variable),每一行是一个观测结果 (observation)。**这个数据格式是后续使用 ggplot 等工具需要的默认格式。
- Each variable must have its own column.
- Each observation must have its own row.
- Each value must have its own cell.
行列数据格式不满足要求的情况
- 一个变量分布在不同的几列
- 一个观测值分布在不同的几行
数据由宽变长:gather()
gather(data, key, value, ..., na.rm = FALSE, convert = FALSE, factor_key = FALSE)
#data:需要被转换的宽形表
#key:将原数据框中的所有列赋给一个新变量 key
#value:将原数据框中的所有值赋给一个新变量 value
#…:指定对哪些列进行操作
#na.rm:是否删除缺失值
# 下面的两种写法等效
peak是行名 不用动 所有是-peak
tmp_tbl <- gather(tmp_data, key = "sample", value = "expression", -peak)
tmp_tbl <- gather(tmp_data, key = "sample", value = "expression", c(2:6))
数据由长变宽 spread()
spread(data, key, value, fill = NA, convert = FALSE, drop = TRUE, sep = NULL)
spread(tmp_tbl,key = "sample", value = "expression")
分列:separate
删除数据集中指定的行或列
删除第1到10行:df[-c(1:10), ] 删除第5到10列:df[ ,-c(5:10)]
按名字删除 无论行列,可以找出对应索引或构造相同长度TRUE/FALSE的向量,把不需要的行/列删除
-which(colnames(df) %in% c("a","b"))
-grep("a|b",colnames(df)
T/F vector
!colnames(df) %in% c("a","b")
!grepl("a|b", colnames(df))
————————————————
subset(df, select=-c(a,b))
dplyr::select(df, -c(a,b))