r tidyr

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了r tidyr相关的知识,希望对你有一定的参考价值。

gather() takes multiple columns, and gathers them into keyvalue pairs: it makes “wide” data longer

spread() takes two columns (key & value) and spreads in to multiple columns, it makes “long” data
wider

#Spread is known by other names in other places: it’s cast in reshape2, unpivot in spreadsheets and unfold in databases


separate() splits a single column into multiple columns //splitting based on some character

unite() combines multiple columns into a single column

messy <- data.frame(
  name = c("Wilbur", "Petunia", "Gregory"),
  a = c(67, 80, 64),
  b = c(56, 90, 50)
)

messy %>% gather(catcolnewname1,valuenewcolname1,a,b) OR
messy %>% gather(catcolnewname1,valuenewcolname1,2:3)


set.seed(10)
messy <- data.frame(
  id = 1:4,
  trt = sample(rep(c('control', 'treatment'), each = 2)),
  work.T1 = runif(4),
  home.T1 = runif(4),
  work.T2 = runif(4),
  home.T2 = runif(4)
)

tidy=messy %>% gather(mycolumn1,mycolumn2,3:6)

################################################### The numbers 3:6 indicate where the numerics are !!!
################################################## or you can exclude columns like this 
DF %>% gather(Quarter, Revenue, -Group, -Year)  ## group and year are excluded

messy=tidy %>% spread(mycolumn1,mycolumn2)
#using spread function to get back into wide format 

tidier <- tidy %>% separate(mycolumn1, into = c("location", "time"), sep = "\\.")
tidy=tidier %>% unite(mycolumn1,location, time, sep = ".")
#using separate to break the column mycolumn1
#using unite to get back tidy

以上是关于r tidyr的主要内容,如果未能解决你的问题,请参考以下文章

R语言 | 数据操作tidyr包

R语言tidyr包separate()函数实战详解:一列裂变为多列

《实习日记》| ​7月21日 R语言学习笔记——tidyr

R语言dplyr包和tidyr包创建交叉表(列联表crosstab)实战

R语言tidyr包Unite()函数实战详解:多个数据列合并为一列

R语言tidyr包gather()函数实战详解:数据收缩从宽表到窄表