收集多组列
Q3.2.1.
, Q3.2.2.
Q3.2.3.
:
df <- data.frame( id = 1:10, time = as.Date('2009-01-01') + 0:9, Q3.2.1. = rnorm(10, 0, 1), Q3.2.2. = rnorm(10, 0, 1), Q3.2.3. = rnorm(10, 0, 1), Q3.3.1. = rnorm(10, 0, 1), Q3.3.2. = rnorm(10, 0, 1), Q3.3.3. = rnorm(10, 0, 1))# Sample data id time Q3.2.1. Q3.2.2. Q3.2.3. Q3.3.1. Q3.3.2. Q3.3.3.1 1 2009-01-01 -0.2059165 -0.29177677 -0.7107192 1.52718069 -0.4484351 -1.215506002 2 2009-01-02 -0.1981136 -1.19813815 1.1750200 -0.40380049 -1.8376094 1.035884823 3 2009-01-03 0.3514795 -0.27425539 1.1171712 -1.02641801 -2.0646661 -0.35353058...
id time loop_number Q3.2 Q3.31 1 2009-01-01 1 -0.20591649 1.527180692 2 2009-01-02 1 -0.19811357 -0.403800493 3 2009-01-03 1 0.35147949 -1.02641801...11 1 2009-01-01 2 -0.29177677 -0.448435112 2 2009-01-02 2 -1.19813815 -1.837609413 3 2009-01-03 2 -0.27425539 -2.0646661...21 1 2009-01-01 3 -0.71071921 -1.2155060022 2 2009-01-02 3 1.17501999 1.0358848223 3 2009-01-03 3 1.11717121 -0.35353058...
tidyr
gather()
得到的数据帧有30行,如预期的那样(10个个体,每个循环3个循环)。但是,收集第二组列不能正常工作-它成功地使这两组合并的列正常工作。 Q3.2
和 Q3.3
,但最后为90行,而不是30行(10个个体的所有组合,Q3.2的3个循环,Q3.3的3个循环;实际数据中每组列的组合将大幅度增加):
df %>% gather(loop_number, Q3.2, starts_with("Q3.2")) %>% gather(loop_number, Q3.3, starts_with("Q3.3")) %>% mutate(loop_number = str_sub(loop_number,-2,-2)) id time loop_number Q3.2 Q3.31 1 2009-01-01 1 -0.20591649 1.527180692 2 2009-01-02 1 -0.19811357 -0.403800493 3 2009-01-03 1 0.35147949 -1.02641801...89 9 2009-01-09 3 -0.58581232 -0.1318702490 10 2009-01-10 3 -2.33393981 -0.48502131
gather()
噜噜哒
Qyouu