R使用列中的多个信息操作数据框

R Manipulate data frame with multiple information in columns

如何根据列 2:7 (day_rep) 的多重信息重塑此数据框,从而获得带有以下列的新 "datlong" 数据框: "trat" "day" "rep" "value"

dat <- read.table(header=T, text='
trat    5_1 5_2 6_1 6_2 7_1 7_2
control 0   0   0   0   12  66
control 0   0   0   0   14  76
control 0   0   0   0   18  78
control 0   0   0   0   16  74
control 0   0   0   0   20  76
urea    0   0   0   12  42  88
urea    0   0   0   8   34  76
urea    0   0   0   6   28  68
urea    0   0   0   4   40  60
urea    0   0   0   10  46  78
')

我们可以使用 gather/separate 来自 tidyr

library(dplyr)
library(tidyr)
gather(dat, dayrep, value, -trat) %>% 
        separate(dayrep, into=c("day", "rep")) %>%
        head()
#     trat day rep value
#1 control   5   1     0
#2 control   5   1     0
#3 control   5   1     0
#4 control   5   1     0
#5 control   5   1     0
#6    urea   5   1     0