如何在R中的数据框中合并重复的行 [英] How to combine duplicate rows in a data frame in R
本文介绍了如何在R中的数据框中合并重复的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出R中的数据帧( my_data ),例如以下内容
Given a dataframe (my_data) in R such as the following
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 )并将其合并。结果应类似于:
I want to transform the dataframe by taking rows with category id values that already exist (e.g category 123) and combine them. The result should look like:
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中执行此操作?
How can I do this in R ?
推荐答案
您可以使用 dplyr
,这对于许多其他类似用途非常有用使用情况如下:
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))
输出为:
# 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
这篇关于如何在R中的数据框中合并重复的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文