在R中创建“数据透视表”,并在每一行中填充因子值

时间:2018-09-02 14:48:39

标签: r dplyr pivot reshape tidyr

我想这样输入日期:

library(plyr)
names(ChickWeight) <- tolower(names(ChickWeight))
ChickWeight$diet.name <- as.factor(revalue(ChickWeight$diet, c("1" = "Grain", "2" = "Grubs", "3" = "Scraps", "4" = "Free Range")))

它将创建:

> head(ChickWeight)
  weight time chick diet diet.name
1     42    0     1    1     Grain
2     51    2     1    1     Grain
3     59    4     1    1     Grain
4     64    6     1    1     Grain
5     76    8     1    1     Grain
6     93   10     1    1     Grain

> tail(ChickWeight)
    weight time chick diet  diet.name
573    155   12    50    4 Free Range
574    175   14    50    4 Free Range
575    205   16    50    4 Free Range
576    234   18    50    4 Free Range
577    264   20    50    4 Free Range
578    264   21    50    4 Free Range

然后从这些数据中提取另一组数据(chick.feed),如下所示:

chick   diet.name
    1       Grain
    2       Grain
    .           .
    .           .
    .           .
   21       Grubs
   22       Grubs
    .           .
    .           .
    .           .
   31      Scraps
   32      Scraps
    .           .
    .           .
    .           .
   49  Free Range
   50  Free Range

即,我想创建一个“数据透视表”(chick.feed),其中每一行(此处为每个chick)的计算值都是字母值(R中的“ factor”) (说)在ChickWeight中该小鸡的所有各行。

(我的问题似乎与this one about converting from long to wide data类似,但并不相同。)

1 个答案:

答案 0 :(得分:0)

无需重塑。只需抓住所需的列并保留唯一的行即可:

unique(ChickWeight[ , c("chick", "diet.name")])