用R收集(tidyr)数据集

时间:2018-01-16 14:23:09

标签: r dataframe reshape tidyr

我想整理和清理数据。

来自Facebook Insights的数据集如下所示:

Video_ID    Albania (AL)    Algeria (DZ)    Argentina (AR)
1   88  79  43
2   2   29  71
3   82  67  91
4   45  41  69
5   14  78  83
6   78  71  39
7   47  13  87

我试过,但我在值列中获得了Video_ID,我想要三列,Video_ID,Location,Value。

tidydata <- gather(df, variable, value)

2 个答案:

答案 0 :(得分:1)

library(tidyverse)

df <- data.frame(Video_ID = 1:7, 
                 Albania_AL = runif(7), 
                 Algeri_DZ = runif(7), 
                 Argentina_AR = runif(7))

df %>% 
  gather(variable, value, -Video_ID)

给出,

   Video_ID     variable        value
1         1   Albania_AL 0.7452748199
2         2   Albania_AL 0.7189716343
3         3   Albania_AL 0.0009818899
4         4   Albania_AL 0.8767066500
5         5   Albania_AL 0.2557317731
6         6   Albania_AL 0.8500135003
7         7   Albania_AL 0.5381997849
8         1    Algeri_DZ 0.6354911723
9         2    Algeri_DZ 0.5642415853
10        3    Algeri_DZ 0.6899371936
11        4    Algeri_DZ 0.5935983881
12        5    Algeri_DZ 0.3544025272
13        6    Algeri_DZ 0.6228319844
14        7    Algeri_DZ 0.2387682097
15        1 Argentina_AR 0.0857397954
16        2 Argentina_AR 0.6284314466
17        3 Argentina_AR 0.2281501831
18        4 Argentina_AR 0.6316785756
19        5 Argentina_AR 0.5259507103
20        6 Argentina_AR 0.8145632301
21        7 Argentina_AR 0.0400777052

答案 1 :(得分:0)

gather(df, key=Country, value, Albania:Argentina)