将多行组合成一行,具有多列数据R.

时间:2018-03-06 20:17:33

标签: r tidyr reshape2

我有一个数据集,其中以不同的方式测量相同的效果,我想比较这些测量。我的数据集如下所示:

Study     MType     ID     Insect     Mean     Sd     N
Alla      Fecundity  1      Aphid      .62      .7628  11
Alla      RGR        1      Aphid      -32.8    7.76   11
Ando      Survival   2      Bee        2.34     .67    8
Ando      RGR        2      Bee        4.56     .34    10
Ando      Fecundity  2      Bee        5.32     4.3    20

我希望按ID号组合行,以便保留每行的MType,Mean,Sd和N(尽管列名需要更改,以便列可以区分)。

希望最终看起来像:

Study ID Insect Fecundity.mean Fecundity.Sd Fecundity.N RGR.mean RGR.Sd...etc

一些困难:

  1. 大约有10种不同的MType
  2. 每个ID号码有2到4个MType
  3. 我已经弄乱了重塑和tidyr,我还没有能够弄清楚如何用它们中的任何一个做到这一点。请帮忙!

2 个答案:

答案 0 :(得分:3)

您可以通过基础R使用reshape。您希望根据以下帖子将数据从长格式转换为宽格式:How to reshape data from long to wide format?

如果您的数据位于data.frame d:

reshape(d, idvar=c("ID", "Study", "Insect"), timevar = "MType", direction="wide")

结果:

  Study ID Insect Mean.Fecundity Sd.Fecundity N.Fecundity Mean.RGR Sd.RGR N.RGR Mean.Survival Sd.Survival N.Survival
1  Alla  1  Aphid           0.62       0.7628          11   -32.80   7.76    11            NA          NA         NA
3  Ando  2    Bee           5.32       4.3000          20     4.56   0.34    10          2.34        0.67          8

答案 1 :(得分:2)

使用tidyr执行此操作并不明显,因为您必须先gather()然后spread()

library(tidyverse)
example <- tribble(
~Study, ~MType, ~ID, ~Insect, ~Mean,   ~Sd,   ~N,
"Alla", "Fecundity",  1, "Aphid", .62, .7628,  11,
"Alla", "RGR",   1, "Aphid", -32.8,  7.76, 11,
"Ando", "Survival", 2, "Bee",   2.34,   .67,  8,
"Ando", "RGR",   2, "Bee",   4.56,   .34,  10,
"Ando", "Fecundity",  2, "Bee",   5.32,   4.3,  20)

gather(example, key = "Statistic", value = "value", Mean, Sd, N) %>%
  unite(col="MType.Statistic", MType, Statistic, sep = ".") %>% 
  spread(key = MType.Statistic, value=value)
#> # A tibble: 2 x 12
#>   Study    ID Insect Fecundity.Mean Fecundity.N Fecundity.Sd RGR.Mean
#> * <chr> <dbl> <chr>           <dbl>       <dbl>        <dbl>    <dbl>
#> 1 Alla   1.00 Aphid           0.620        11.0        0.763   -32.8 
#> 2 Ando   2.00 Bee             5.32         20.0        4.30      4.56
#> # ... with 5 more variables: RGR.N <dbl>, RGR.Sd <dbl>,
#> #   Survival.Mean <dbl>, Survival.N <dbl>, Survival.Sd <dbl>