R语言 tidyr包的三个重要函数:gather,spread,separate的用法和举例

本文介绍了R语言tidyr包中的三个重要函数:gather用于将二维表转换为规范的二维表,separate用于分割包含多个变量的列,spread则用于扩展表,将一列的值拆分为多列。通过实例展示了这三个函数的具体用法和参数设置,帮助理解tidyr包在数据整理中的应用。
摘要由CSDN通过智能技术生成

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(

  • 58
    点赞
  • 257
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值