本文介绍了R:提取一列中的唯一值,并按另一列中的值分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我原以为可以用data.table解决这个问题,但是看起来有点困难。我的数据框如下所示:

I had thought I could solve this with data.table but looks like it is a bit more difficult. My dataframe looks like this:

userID1   A
userID1   A
userID1   B
userID2   A
userID2   A

输出应该看起来像这样:

The output is supposed to look like this:

userID1   A
userID1   B
userID2   A

基本上为每个唯一的用户和项目出现创建一行。大多数示例都是关于计数唯一元素,而不是实际提取这些元素。有建议吗?

Basically create a row for each unique user and item occurence. Most of the examples are about counting unique elements but not about actually extracting these. Any suggestions?

推荐答案

这是一个dplyr解决方案,应获得这些结果

This is a dplyr solution that should get those results

library(dplyr)

df <- data.frame(user = c(rep("userID1",3), rep("userID2",2)),
                 group = c("A","A","B","A","A"),
                 stringsAsFactors = FALSE)


df <- df %>%
      group_by(user, group) %>%
      filter(row_number() == 1)

这篇关于R:提取一列中的唯一值,并按另一列中的值分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 13:06