tidyr用于数据处理,可以实现数据长格式和宽格式之间的相互转换,这里所指的长格式数据就是一个观测对象由多行组成,而宽数据格式则是一个观测仅由一行组成。除此之外,tidyr还可以对数据进行拆分和合并,同时也能够对缺失值进行简单的处理。tidyr的转换函数gather(宽到长)和spread(长到宽)所需参数少,逻辑上更易理解,自始至终都围绕着data,key、value三个参数来进行设定,对比其它R语言长宽格式互换的实现方式,个人认为tidyr操作性还是比较突出的。
1. gather实现wide 到 long 转换
tidyr中的gather函数类似于reshape2中的melt函数,可实现将宽格式数据转换为长数据格式。
gather(data, key, value, ..., na.rm = FALSE, convert = FALSE, factor_key = FALSE)
data:需要被转换的宽形data.frame
key:将原数据框中的所有列赋给一个新变量key
value:将原数据框中的所有值赋给一个新变量value
…:可以指定哪些列聚到同一列中,可用于选择两列之间的所有列col1:coln, 排除列-coln
na.rm:是否删除缺失值,默认为FALSE不删除
convert:为TRUE时会自动在key列上使用type.convert函数,默认值为FALSE
factor_key:FALSE时key值为字符向量,TRUE时key值为factor类型
require(tidyr)
#将mtcars的所有列聚合成两列
gather(mtcars, attr, value)
#聚合mpg和gear之间的列
gather(mtcars, attr, value, mpg:gear)
#仅聚合mpg和wt变量,其余变量保持不变
gather(mtcars, attr, value, mpg, wt)
require(dplyr)
#添加car列到mtcars中
mtcars$car <- rownames(mtcars)
#除了car列,将mtcars的所有列聚合成两列
gather(mtcars, attr, value, -car)
mtcars %>% gather(attr, value, -car)
#聚合mpg和gear之前的列
mtcars %>% gather(attr, value, mpg:gear)
mtcars %>% gather(mpg:gear, key = "attr", value = "value")
#仅聚合gear和carb变量,其余变量保持不变
mtcars %>% gather(attr ,value ,gear ,carb)
mtcars %>% gather(gear ,carb ,key = "attr", value = "value")
2. spread实现long 到wide转换
tidyr中的spread函数类似于reshape2中的cast函数,可实现将长格式数据转换为宽数据格式。
spread(data, key, value, fill = NA, convert = FALSE, drop = TRUE, sep = NULL)
data:为需要转换的长形data.frame
key:设置需要扩宽的类别变量
value:设置需要扩宽的变量的度量值
fill:对于缺失值,可将fill的值赋值给被转型后的缺失值
convert:为TRUE时会自动在新列上使用type.convert函数,其中as.is = TRUE,默认值为FALSE
drop: 为FALSE保留factor的level,使用fill的值填充missing的值
sep:为默认值NULL时,新列名使用key中的值,非NULL时,新列名为<key_name><sep><key_value>
require(dplyr)
mtcars$car <- rownames(mtcars)
longformat <- gather(mtcars, attr, value, -car)
#还原长格式为原宽格式数据
spread(longformat, attr, value)
longformat %>% spread(attr, value)
#设置sep,新的列名为<key_name><sep><key_value>的形式
spread(longformat, attr, value, sep = '|')
#还原长格式为原宽格式数据,car列的值转换为每一个列
spread(longformat, car, value)
longformat %>% spread(car, value)
df <- data.frame(x = c("a", "b"), y = c(3, 4), z = c(5, 6))
#转换为宽格式再转换为长格式,实际还原为原df,只是变量顺序不同
df %>% spread(x, y) %>% gather(x, y, a:b, na.rm = TRUE)
df <- data.frame(row = rep(c(1, 51), each = 3),
var = c("Sepal.Length", "Species", "Species_num"),
value = c(5.1, "setosa", 1, 7.0, "versicolor", 2))
#对于混合类型的value列,默认convert = FALSE,转换的新列为factor类型
df %>% spread(var, value)
#设置convert = TRUE,保留原类型
df %>% spread(var, value, convert = TRUE)
————————————————
版权声明:本文为CSDN博主「Kingsley_W」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/wltom1985/article/details/107902563