【问题标题】:keep only one row per grouped column based on column value根据列值,每个分组列只保留一行
【发布时间】:2018-11-13 22:18:38
【问题描述】:

假设我在 R 中有一个 data.frame

User  Hardware
a     mac
a     tablet
a     laptop
b     laptop
b     tablet
c     tablet
c     mac

如果用户有 mac,我只想保留 mac 行,如果用户没有 mac,则保留所有行。

我想要的输出

User Hardware
a    mac
b    laptop
b    tablet
c    mac

我一直在寻找和尝试,但无法找到解决方案。

【问题讨论】:

    标签: r dataframe dplyr


    【解决方案1】:

    这将从df 中删除具有mac 的非mac 行。

    df = read.table(text="User  hardware
    a       mac
    a       tablet
    a       laptop
    b       laptop
    b       tablet
    c       tablet
    c       mac", header = TRUE)
    
    mac_users = as.character(unique(df$User[df$hardware == "mac"]))
    df = df[!((df$User %in% mac_users) & (df$hardware != "mac")),]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-11
      • 2021-01-16
      • 1970-01-01
      • 2020-04-15
      • 2019-11-20
      • 2022-12-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多