蛮力我会说只使用dplyr
library(dplyr)
df <- data.frame(Timepoint=c(0L, 7L, 14L, 21L, 28L), Group1=c(50L, 60L, 66L, 88L, 90L),
Error_Group1=c(3, 4, 6, 8, 2), Group2=c(30L, 60L, 90L, 120L, 150L),
Error_Group2=c(10L, 14L, 16L, 13L, 25L), Group3=c(44L, 78L, 64L, 88L, 91L),
Error_Group3=c(2L, 13L, 16L, 4L, 9L))
df <- lapply(1:3, function(x){
temp <- df %>% select(Timepoint, ends_with(as.character(x))) %>% mutate(Group=x)
names(temp) <- c("Timepoint", "Measure", "Error", "Group")
temp <- temp %>% select(Timepoint, Group, Measure, Error)
})
df <- do.call(rbind, df)
df
也更优雅tidyr
一点
library(dplyr); library(tidyr)
df <- df %>% gather(temp, Timepoint)
names(df) <- c("Timepoint", "temp", "values")
df <- df %>% mutate(Group = sub("\\D+", "", temp), temp=sub("\\d", "", temp)) %>%
spread(temp, values)
names(df) <- c("Timepoint", "Group", "Error", "Measure")
df