您可以尝试此解决方案。我使用列表来达到你想要的:
library(reshape2)
#Data
L1 <- list(structure(list(ID = 1:3, `1h` = c(3L, 1L, 7L), `2h` = c(5L,
8L, 3L), `3h` = c(6L, 2L, 9L)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(ID = 1:3, `1h` = c(9L, 0L, 2L), `2h` = c(0L,
3L, 4L), `3h` = c(0L, 1L, 7L)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(ID = 1:3, `1h` = c(3L, 5L, 7L), `2h` = c(1L,
5L, 0L), `3h` = c(0L, 0L, 0L)), class = "data.frame", row.names = c(NA,
-3L)))
L2 <- list(structure(list(ID = 1:3, `1h` = c(7L, 1L, 7L), `2h` = c(3L,
8L, 3L), `3h` = c(0L, 2L, 9L)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(ID = 1:3, `1h` = c(8L, 9L, 2L), `2h` = c(0L,
5L, 4L), `3h` = c(1L, 3L, 7L)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(ID = 1:3, `1h` = c(0L, 0L, 3L), `2h` = c(2L,
5L, 5L), `3h` = c(9L, 9L, 4L)), class = "data.frame", row.names = c(NA,
-3L)))
L3 <- list(structure(list(ID = 1:3, `1h` = c(7L, 1L, 7L), `2h` = c(3L,
8L, 3L), `3h` = c(0L, 2L, 9L)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(ID = 1:3, `1h` = c(8L, 9L, 2L), `2h` = c(0L,
5L, 4L), `3h` = c(1L, 3L, 7L)), class = "data.frame", row.names = c(NA,
-3L)), structure(list(ID = 1:3, `1h` = c(0L, 0L, 3L), `2h` = c(2L,
5L, 5L), `3h` = c(9L, 9L, 4L)), class = "data.frame", row.names = c(NA,
-3L)))
#Format function
formatf <- function(x)
{
y <- reshape2::melt(x,id.vars = 'ID')
return(y)
}
#Apply
M1 <- lapply(L1,formatf)
M2 <- lapply(L2,formatf)
M3 <- lapply(L3,formatf)
#Merge function
fmerge <- function(a,b,c)
{
d1 <- merge(a,b,by=c('ID','variable'))
d2 <- merge(d1,c,by=c('ID','variable'))
return(d2)
}
#Apply
LL=mapply(fmerge,M1,M2,M3,SIMPLIFY = FALSE)
#Format to export
names(LL)<-paste0('Group',1:length(LL))
#Bind all
DF <- do.call(rbind,LL)
#Assign group and format id
DF$Group <- rownames(DF)
DF <- DF[,c(6,1:5)]
rownames(DF)<-NULL
DF$Group <- gsub("\\..*","",DF$Group)
#Write to csv
write.csv(DF,file='DF.csv')
你会得到这个。我希望这会有所帮助。
Group ID variable value.x value.y value
1 Group1 1 1h 3 7 7
2 Group1 1 2h 5 3 3
3 Group1 1 3h 6 0 0
4 Group1 2 1h 1 1 1
5 Group1 2 2h 8 8 8
6 Group1 2 3h 2 2 2
7 Group1 3 1h 7 7 7
8 Group1 3 2h 3 3 3
9 Group1 3 3h 9 9 9
10 Group2 1 1h 9 8 8
11 Group2 1 2h 0 0 0
12 Group2 1 3h 0 1 1
13 Group2 2 1h 0 9 9
14 Group2 2 2h 3 5 5
15 Group2 2 3h 1 3 3
16 Group2 3 1h 2 2 2
17 Group2 3 2h 4 4 4
18 Group2 3 3h 7 7 7
19 Group3 1 1h 3 0 0
20 Group3 1 2h 1 2 2
21 Group3 1 3h 0 9 9
22 Group3 2 1h 5 0 0
23 Group3 2 2h 5 5 5
24 Group3 2 3h 0 9 9
25 Group3 3 1h 7 3 3
26 Group3 3 2h 0 5 5
27 Group3 3 3h 0 4 4