tidyr是Hadley(Tidy Data的作者Hadley Wickham)写的非常有用、并且经常会使用到的包,常与dplyr包结合使用(这个包也是他写的)
准备工作:
首先安装tidyr包(一定要加引号,不然报错)
install.packages("tidyr")
载入tidyr(可以不加引号)
library(tidyr)
gather()
gather函数类似于Excel(2016起)中的数据透视的功能,能把一个变量名含有变量的二维表转换成一个规范的二维表(类似数据库中关系的那种表,具体看例子)
我们先 >?gather,看看官方文档说明:
gather {tidyr} R Documentation
Gather columns into key-value pairs.
Description
Gather takes multiple columns and collapses into key-value pairs, duplicating all other columns as needed. You use gather() when you notice that you have columns that are not variables.
Usage
gather(data, key = "key", value = "value", ..., na.rm = FALSE,
convert = FALSE, factor_key = FALSE)
Arguments
data
A data frame.
key, value
Names of new key and value columns, as strings or symbols.
This argument is passed by expression and supports quasiquotation (you can unquote strings and symbols). The name is captured from the expression with rlang::ensym() (note that this kind of interface where symbols do not represent actual objects is now discouraged in the tidyverse; we support it here for backward compatibility).
... (这是一个参数)
A selection of columns. If empty, all variables are selected. You can supply bare variable names, select all variables between x and z with x:z, exclude y with -y. For more options, see the dplyr::select(