如何在R中的数据框中组合重复的行

时间:2016-12-09 12:33:23

标签: r dataframe transformation

给出R中的数据框( my_data ),如下所示

category  Keyword1 Keyword2 Keyword3 Keyword4 Keyword5 Keyword6 Keyword7 Keyword8
123         0        1         1       0         0        0       0         1
155         1        0         0       0         1        0       1         1
144         0        0         1       0         0        0       1         1
123         1        1         0       0         0        0       1         1

我想通过获取已经存在的类别id值的行(例如类别 123 )来转换数据框并将它们组合起来。结果应如下所示:

category Keyword1 Keyword2 Keyword3 Keyword4 Keyword5 Keyword6 Keyword7 Keyword8
123         1        1         1       0         0        0       0         1
155         1        0         0       0         1        0       1         1
144         0        0         1       0         0        0       1         1

我怎样才能在R中这样做?

1 个答案:

答案 0 :(得分:1)

You can use dplyr, which is useful for many other such use cases as follows:

library(dplyr)
my_data %>% group_by(category) %>% summarise_each(funs(max)) 

Output is:

# A tibble: 3 × 9
  category Keyword1 Keyword2 Keyword3 Keyword4 Keyword5 Keyword6 Keyword7 Keyword8
     <int>    <int>    <int>    <int>    <int>    <int>    <int>    <int>    <int>
1      123        1        1        1        0        0        0        1        1
2      144        0        0        1        0        0        0        1        1
3      155        1        0        0        0        1        0        1        1
相关问题