﻿ 如何使用“四重嵌套”将宽数据帧转换为多级结构的长数据帧？ - 代码日志

#### 如何使用“四重嵌套”将宽数据帧转换为多级结构的长数据帧？

``````### Elements of the variable names
measurementMomentsVector <- c("t0", "t1");
interventionTypesVector <- c("fear", "know", "scd");
nrOfInterventionsSimultaneouslyVector <- c(1, 2, 3);
behaviorDomainsVector <- c("diet", "pox", "alc", "smoking", "traff", "adh");

### Generate a vector with all variable names
variableNames <-
apply(expand.grid(measurementMomentsVector,
interventionTypesVector,
nrOfInterventionsSimultaneouslyVector,
behaviorDomainsVector),
1, paste0, collapse="_");

### Generate 5 'participants' worth of data
wideData <- data.frame(matrix(rnorm(5*length(variableNames)), nrow=5));

### Assign names
names(wideData) <- variableNames;

### Add unique id variable for every participants
wideData\$id <- 1:5;
``````

``````  t0_fear_1_diet t1_fear_1_diet t0_know_1_diet t1_know_1_diet t0_scd_1_diet
1     -0.9338191      0.9747453      1.0069036      0.3500103  -0.844699708
2      0.8921867      1.3687834     -1.2005791      0.2747955   1.316768219
3      1.6200200      0.5245470     -1.2910586      1.3211912  -0.174795144
4      0.1543738      0.7535642      0.4726131     -0.3464789  -0.009190702
5     -1.3676692     -0.4491574     -2.0902003     -0.3484678  -2.537501824
``````

``````longData <- reshape(wideData, varying=1:(ncol(wideData)-1),
idvar="id",
sep="_", direction="long")
``````

``````Error in guess(varying) :
failed to guess time-varying variables from their names
``````

>将您的数据融入长数据框架(或者像我一样,在长数据表中)
>将包含所有标签的变量列拆分为每个所需分组变量的单独列.

``````library(data.table)
longData <- melt(setDT(wideData), id.vars="id")
longData[, c("moment", "intervention", "number", "behavior") :=
tstrsplit(variable, "_", type.convert = TRUE)
][, variable:=NULL]
``````

``````> head(longData,15)
id       value moment intervention number behavior
1:  1 -0.07747254     t0         fear      1     diet
2:  2 -0.76207379     t0         fear      1     diet
3:  3  1.15501244     t0         fear      1     diet
4:  4  1.24792369     t0         fear      1     diet
5:  5 -0.28226121     t0         fear      1     diet
6:  1 -1.04875354     t1         fear      1     diet
7:  2 -0.91436882     t1         fear      1     diet
8:  3  0.72863487     t1         fear      1     diet
9:  4  0.10934261     t1         fear      1     diet
10:  5 -0.06093002     t1         fear      1     diet
11:  1 -0.70725760     t0         know      1     diet
12:  2  1.06309003     t0         know      1     diet
13:  3  0.89501164     t0         know      1     diet
14:  4  1.48148316     t0         know      1     diet
15:  5  0.22086835     t0         know      1     diet
``````

``````library(splitstackshape)
longData <- cSplit(longData, sep="_", "variable", "wide", type.convert=TRUE)
names(longData) <- c("id","value","moment","intervention","number","behavior")
``````

``````library(tidyr)
separate(longData, variable, c("moment", "intervention", "number", "behavior"), sep="_", remove=TRUE)
``````