R 使用多个不同类型的重复列从宽格式到长格式进行数据争用

R 使用多个不同类型的重复列从宽格式到长格式进行数据争用,r,dplyr,tidyr,data-wrangling,R,Dplyr,Tidyr,Data Wrangling,数据集描述多个集群的多个重复测量,每个测量集群对包含在单个列中。我想将数据整理成一个长(er)格式,这样一列提供集群的信息,但每个度量都保留在自己的列中 # Current format df_wider <- data.frame( id = 1:5, fruit_1 = sample(fruit, size = 5), date_1 = sample(seq(as.Date('2020/01/01'), as.Date('2020/05/01'), by="day"), 5

数据集描述多个集群的多个重复测量,每个测量集群对包含在单个列中。我想将数据整理成一个长(er)格式,这样一列提供集群的信息,但每个度量都保留在自己的列中

# Current format
df_wider <- data.frame(
  id = 1:5,
  fruit_1 = sample(fruit, size = 5),
  date_1 = sample(seq(as.Date('2020/01/01'), as.Date('2020/05/01'), by="day"), 5),
  number_1 = sample(1:100, 5),
  fruit_2 = sample(fruit, size = 5),
  date_2 = sample(seq(as.Date('2020/01/01'), as.Date('2020/05/01'), by="day"), 5),
  number_2 = sample(1:100, 5),
  fruit_3 = sample(fruit, size = 5),
  date_3 = sample(seq(as.Date('2020/01/01'), as.Date('2020/05/01'), by="day"), 5),
  number_3 = sample(1:100, 5)
)

# Desired format
df_longer <- data.frame(
  id = rep(1:5, each = 3),
  cluster = rep(1:3, 5),
  fruit = sample(fruit, size = 15),
  date = sample(seq(as.Date('2020/01/01'), as.Date('2020/05/01'), by="day"), 15),
  number = sample(1:100, 15)
)
#当前格式
df_你可以做:

library(tidyr)
图书馆(dplyr)
df_加宽%>%pivot_加宽(-id,
名称\u模式=“(.*)\u(\\d)”,
名称_to=c(“.value”,“cluster”))
#一个tibble:15x5
id簇水果日期编号
橄榄2020-04-21 50
接骨木2020-02-23 59
3 1 3切里莫亚2020-03-07 9
枣树2020-03-22 88
5普通话2020-03-06 45
6 2 3葡萄2020-04-23 78
7 3 1螺母2020-01-26 53
哈密瓜2020-01-27 70
9 3榴莲2020-02-15 39
10 4 1辣椒2020-03-17 60
葡萄干2020-04-14 20
12 4 3 cloudberry 2020-03-11 4
13 5 1蜜露2020-01-04 81
14 5 2石灰2020-03-23 53
15 5 3乌格利水果2020-01-13 26

我们可以使用
数据表中的
熔化

library(data.table)
melt(setDT(df_wider), measure = patterns('^fruit', '^date', '^number' ), 
      value.name = c('fruit', 'date', 'number'), variable.name = 'cluster')
#    id cluster        fruit       date number
# 1:  1       1         date 2020-04-16     17
# 2:  2       1       quince 2020-01-27      7
# 3:  3       1      coconut 2020-04-19     33
# 4:  4       1  pomegranate 2020-02-27     55
# 5:  5       1    persimmon 2020-02-20     62
# 6:  1       2   kiwi fruit 2020-01-14    100
# 7:  2       2    cranberry 2020-03-15     97
# 8:  3       2     cucumber 2020-03-16      5
# 9:  4       2    persimmon 2020-03-06     81
#10:  5       2         date 2020-04-17     30
#11:  1       3      apricot 2020-04-13     86
#12:  2       3       banana 2020-04-17     42
#13:  3       3     bilberry 2020-02-23     88
#14:  4       3 blackcurrant 2020-02-25     10
#15:  5       3       raisin 2020-02-09     87

我写问题比你回答问题花的时间长。你太快了,stackoverflow还不让我把它标记为正确答案。真令人印象深刻,谢谢你。我喜欢这个网站。不客气;)你很幸运,因为我实际上在学习如何使用
名称\u模式
,所以,你的问题对我来说是一个很好的练习。我应该在20小时前问这个问题,当我第一次意识到这对我来说是个问题时……我认为先尝试一下自己总是好的;)那么你最好理解答案;)