根据列值,每个分组列仅保留一行

时间:2018-11-13 22:18:38

标签: r dataframe dplyr

假设我在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

我一直在搜索并尝试,但是找不到解决方案。

1 个答案:

答案 0 :(得分:0)

这将从df中删除具有macs的用户的非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")),]