Data-整理数据Reshape

在R中准备和重塑数据以便于分析

在前面,我们描述了R编程的要点,并提供了将数据导入R的快速入门指南。下一个关键步骤是将数据设置为一致的数据结构,以便于分析。在这里,您将学习准备和重塑数据的现代约定,以便在R中进行分析。

1)R中的Tibble数据格式:处理数据的最佳和现代方式

2)Tidyr:用R重塑数据以便于分析的关键步骤


(1)R中的Tibble数据格式:处理数据的最佳和现代方式

预备任务

安装和加载tibble包

创建新的tibble

将数据转换为tibble

tibbles相对于数据框的优势

在前面,我们描述了R编程的要点,并提供了将数据导入R的快速入门指南。传统的R基函数read.table()、read.delim()和read.csv()将数据作为数据框导入R。然而,最现代的R包readr提供了几个函数(read_delim()、read_tsv()和read_csv()),这些函数比R基函数更快,并将数据作为tbl_df(发音为“tibble diff”)导入R。

tbl_df object是一个提供更好输出方法的数据框,在处理大型数据集时非常有用。

在本文中,我们将介绍由Hadley Wickham开发的tibble R包。tibble R包为创建tibbles提供了易于使用的功能,这是对数据框的现代反思。


准备工作

启动 RStudio 

安装和加载 tibble package

# Installing

> install.packages("tibble")

# Loading

> library("tibble")

创建一个新的 tibble

要通过组合多个向量创建新的tibble,请使用函数 tibble():

# Create

> friends_data<-tibble(name=c("Nicolas","Thierry","Bernard","Jerome"),age=c(27,25,29,26),height=c(180,170,185,169),married=c(TRUE,FALSE,TRUE,TRUE))

# Print

> friends_data

和传统的 data.frame() 相比, 现代的 tibble():

never converts string as factor从不将字符串转换为因子

never changes the names of variables从不更改变量名

never create row names从不创建行名称

Convert your data as a tibble将数据转换为tibble

注意,如果使用readr包将数据导入R,则不需要执行此步骤。readr已将数据导入为 tbl_df.

要将传统数据转换为tibble,请使用函数  as_tibble() [在tibble包中],该函数用于数据框、列表、矩阵和表:

library("tibble")

# Loading data

data("iris")

# Class of iris

class(iris)

[1] "data.frame"

# Print the frist 6 rows

head(iris,6)

# Convert iris data to a tibble

my_data<-as_tibble(iris)

class(my_data)

[1] "tbl_df"    "tbl"        "data.frame"

# Print my data
my_data

# A tibble: 150 x 5

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species

          <dbl>       <dbl>        <dbl>       <dbl> <fct>  

 1          5.1         3.5          1.4         0.2 setosa 

 2          4.9         3            1.4         0.2 setosa 

 3          4.7         3.2          1.3         0.2 setosa 

 4          4.6         3.1          1.5         0.2 setosa 

 5          5           3.6          1.4         0.2 setosa 

 6          5.4         3.9          1.7         0.4 setosa 

 7          4.6         3.4          1.4         0.3 setosa 

 8          5           3.4          1.5         0.2 setosa 

 9          4.4         2.9          1.4         0.2 setosa 

10          4.9         3.1          1.5         0.1 setosa 

# ... with 140 more rows

如果要将tibble返回到数据框,请使用函数 as.data.frame(my_data).

tibbles相对于数据框的优势:

1)Tibbles有很好的输出方法,只显示前10行和屏幕上的所有列。这在处理大型数据集时非常有用。

2)输出时,指定每列的数据类型(见下文):

<dbl>: for double

<fct>: for factor

<chr>: for character

<lgl>: for logical

可以更改默认输出外观,如下所示:

更改输出最大行和最小行:options(tibble.print_max=20,tibble.print_min=6)

始终显示所有行:options(tibble.print_max=Inf)

始终显示所有列:options(tibble.width=Inf)

提取tibble将始终返回tibble。与传统的data.frames相比,不需要使用drop=FALSE。

总结

创建tibble:  tibble()

将数据转换为tibble:  as_tibble()

更改tibble的默认输出外观: options(tibble.print_max = 20, tibble.print_min = 6)


2)Tidyr:用R重塑数据以便于分析的关键步骤

什么是整洁的数据集?

预备任务

使用Tidyr软件包重塑数据

安装和加载tidyr

示例数据集

collect():将列折叠成行

Spread():将两列扩展为多列

unite():将多列合并为一个

split():将一列分成多个

链接多个操作

总结


之前,我们介绍了R编程的基本原理,并提供了将数据导入R以及将数据转换为tibble数据格式的快速入门指南,这是处理数据的最佳和现代方式。

在这里,我们将学习如何组织(或重塑)数据,以便使分析更容易。这个过程叫做整理数据。

Tidyr:使用R对数据进行关键步骤重塑,以便于分析

什么是整洁的数据集?

在以下情况下,数据集称为tidy:

每列代表一个变量

每一行代表一个观察

与tidy相反的是凌乱的数据,它对应于数据的任何其他排列。


使数据保持整洁的格式对于简化数据分析任务(包括数据操作、建模和可视化)至关重要。

由Hadley Wickham开发的R包tidyr提供了一些功能,帮助您将数据集组织(或重塑)为整洁的格式。它特别设计用于与magritr和dplyr结合,以构建可靠的数据分析管道。

预备任务

启动RStudio:运行RStudio并设置工作目录

导入数据:将数据导入R

使用tidyr包重塑数据

tidyr包提供四个功能,帮助您更改数据集的布局:

gather():将列聚集(折叠)成行

spread():将行分散到列中

separate():将一列分隔成多列

unite():将多个列合并为一个列

安装和加载 tidyr 包

# Installing

install.packages("tidyr")

# Loading

library("tidyr")

示例数据集

我们将使用R内置的USArrests数据集。我们首先设置一个小数据集,它将在下一节中用作示例数据集:

>my_data <- USArrests[c(1, 10, 20, 30), ]

>my_data

行名是洲名,所以让我们使用函数cbind()在数据中添加一个名为“state”的列。这将使数据整理和分析更容易。

>my_data <- cbind(state = rownames(my_data), my_data)

>my_data

gather():将列折叠成行

函数gather()将多个列折叠为键值对。它从“宽”数据格式生成“长”数据格式。它是melt()函数的另一种替代方法[在reforme2包中]。


简要形式:

gather(data, key, value, ...)

data: 一个数据框

key, value: Names of key and value columns to create in output要在输出中创建的键列和值列的名称

: Specification of columns to gather. Allowed values are:

        variable names

        if you want to select all variables between a and e, use a:e

        if you want to exclude a column name y use -y

        for more options, see: dplyr::select()

使用示例:

Gather all columns except the column state

my_data2<-gather(my_data,key="arrest_attribute",value="arrest_estimate",-state)

my_data2

请注意,所有列名(state除外)都已折叠为一个键列(此处为“逮捕属性”)。它们的值已放入值列(此处为“逮捕估算”)。

Gather only Murder and Assault columns

my_data2 <- gather(my_data,key = "arrest_attribute",value = "arrest_estimate",Murder, Assault)

my_data2

注意,谋杀和袭击这两个纵队已经合并,其余的纵队(州、城市和强奸)是重复的。

Gather all variables between Murder and UrbanPop

my_data2<-gather(my_data,key="arrest_attribute",value="arrest_estimate",Murder:UrbanPop)

my_data2

如何在R函数中以编程方式使用gather()?

您应该使用函数gather_(),它接受包含列名的字符向量,而不是不带引号的列名

简化语法如下:

gather_(data, key_col, value_col, gather_cols)

data: a data frame

key_colvalue_col: Strings specifying the names of key and value columns to create

gather_cols: Character vector specifying column names to be gathered together into pair of key-value columns.

示例:

gather_(my_data,

      key_col = "arrest_attribute",

      value_col = "arrest_estimate",

      gather_cols = c("Murder", "Assault"))

spread(): spread two columns into multiple columns

The function spread() does the reverse of gather(). It takes two columns (key and value) and spreads into multiple columns. It produces a “wide” data format from a “long” one. It’s an alternative of the function cast() [in reshape2package].

Simplified format:

spread(data,key,value)

data: A data frame

key: The (unquoted) name of the column whose values will be used as column headings.

value:The (unquoted) names of the column whose values will populate the cells.

使用示例:

Spread “my_data2” to turn back to the original data:

>my_data3<-spread(my_data2,key="arrest_attribute",value="arrest_estimate")

>my_data3

      state Rape Assault Murder UrbanPop

1    Alabama 21.2    236  13.2      58

2    Georgia 25.8    211  17.4      60

3  Maryland 27.8    300  11.3      67

4 New Jersey 18.8    159    7.4      89

How to use spread() programmatically inside an R function?

You should use the function spread_() which takes strings specifying key and value columns instead of unquoted column names

The simplified syntax is as follow:

spread_(data,key_col,value_col)

data: a data frame.

key_colvalue_col: Strings specifying the names of key and value columns.

示例:

spread_(my_data2,key="arrest_attribute",value="arrest_estimate")

unite(): Unite multiple columns into one

The function unite() takes multiple columns and paste them together into one.

Simplified format:

unite(data,col,...,sep="_")

data: A data frame

col: The new (unquoted) name of column to add.

sep: Separator to use between values

示例:

The R code below uses the data set “my_data” and unites the columns Murder and Assault

>my_data4<-unite(my_data,col="Murder_Assault",Murder,Assault,sep="_")my_data4

                state Murder_Assault UrbanPop Rape

Alabama      Alabama      13.2_236      58 21.2

Georgia      Georgia      17.4_211      60 25.8

Maryland    Maryland      11.3_300      67 27.8

New Jersey New Jersey        7.4_159      89 18.8

How to use unite() programmatically inside an R function?

You should use the function unite_() as follow.

unite_(data,col,from,sep="_")

data: A data frame.

col: String giving the name of the new column to be added

from: Character vector specifying the names of existing columns to be united

sep: Separator to use between values.

As an example, type this:

unite_(my_data,col="Murder_Assault",from=c("Murder","Assault"),sep="_")

separate(): separate one column into multiple

The function sperate() is the reverse of unite(). It takes values inside a single character column and separates them into multiple columns.

Simplified format:

separate(data,col,into,sep="[^[:alnum:]]+")

data: A data frame

col: Unquoted column names

into: Character vector specifying the names of new variables to be created.

sep: Separator between columns:

If character, is interpreted as a regular expression.

If numeric, interpreted as positions to split at. Positive values start at 1 at the far-left of the string; negative value start at -1 at the far-right of the string.

Examples of usage:

Separate the column “Murder_Assault” [in my_data4] into two columns Murder and Assault:

separate(my_data4,col="Murder_Assault",into=c("Murder","Assault"),sep="_")

                state Murder Assault UrbanPop Rape

Alabama      Alabama  13.2    236      58 21.2

Georgia      Georgia  17.4    211      60 25.8

Maryland    Maryland  11.3    300      67 27.8

New Jersey New Jersey    7.4    159      89 18.8

How to use separate() programmatically inside an R function?

You should use the function separate_() as follow.

separate_(data,col,into,sep="[^[:alnum:]]+")

data: A data frame.

col: String giving the name of the column to split

into: Character vector specifying the names of new columns to create

sep: Separator between columns (as above).

As an example, type this:

separate_(my_data4,col="Murder_Assault",into=c("Murder","Assault"),sep="_")

Chaining multiple operations

It’s possible to combine multiple operations using maggrittr forward-pipe operator : %>%.

For example, x %>% f is equivalent to f(x).

In the following R code:

first, my_data is passed to gather() function

next, the output of gather() is passed to unite() function

my_data%>%gather(key="arrest_attribute",value="arrest_estimate",Murder:UrbanPop)%>%unite(col="attribute_estimate",arrest_attribute,arrest_estimate)


总结

您应该使用R软件包tidyr整理数据,以简化数据分析,该软件包提供以下功能。

将多列折叠为键值对(长数据格式):gather(data, key, value, …)

将键值对传播到多列(宽数据格式)中:spread(data, key, value)

将多列合并为一个:unite(data,col,…)

将一列分成多列:split(data,col,into)

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

推荐阅读更多精彩内容