【问题标题】:Selecting distinct values of a column with specific values of other columns选择具有其他列的特定值的列的不同值
【发布时间】:2021-02-15 22:10:40
【问题描述】:

我有以下数据集,其中 ID 有重复项,其他列是范围从 0 t0 2 的分类列。如果可用,我想选择其他列的值不为零的唯一 ID。数据如下:

 ID      X     Y     R      Z 
  1      0     2     0      1
  1      0     2     0      0
  2      1     0     0      1
  3      1     1     0      1
  3      1     1     1      1
  4      0     0     1      0
  4      0     1     1      0

我最喜欢的结果是:

 ID      X     Y     R      Z 
  1      0     2     0      1
  2      1     0     0      1
  3      1     1     1      1
  4      0     1     1      0

我正在使用 dplyrgroup_by

谢谢!

【问题讨论】:

  • baseR 选项aggregate(. ~ ID, df1, max)

标签: r dplyr group-by duplicates


【解决方案1】:

我们可以在group_by 之后使用带有if/else 的条件

library(dplyr)
df1 %>%
   group_by(ID) %>% 
   summarise(across(everything(), ~ if(all(. == 0)) 0 
       else unique(.[. !=0])), .groups = 'drop')

-输出

# A tibble: 4 x 5
#     ID     X     Y     R     Z
#  <int> <dbl> <dbl> <dbl> <dbl>
#1     1     0     2     0     1
#2     2     1     0     0     1
#3     3     1     1     1     1
#4     4     0     1     1     0

数据

df1 <- structure(list(ID = c(1L, 1L, 2L, 3L, 3L, 4L, 4L), X = c(0L, 
0L, 1L, 1L, 1L, 0L, 0L), Y = c(2L, 2L, 0L, 1L, 1L, 0L, 1L), R = c(0L, 
0L, 0L, 0L, 1L, 1L, 1L), Z = c(1L, 0L, 1L, 1L, 1L, 0L, 0L)),
class = "data.frame", row.names = c(NA, 
-7L))

【讨论】:

  • 谢谢,我可以在几分钟内接受您的回答。我会尝试您的代码并会与您联系,再次感谢
  • @akrun,你能解释一下摘要里面的部分吗?
  • @akrun.我收到一个错误,因为我在summarise 部分中有unexpected bracket and unexpected comma
  • @Alex 我再次测试了代码。抱歉,无法收到您提到的错误。是不是因为你有不同的packageVersion('dplyr')
【解决方案2】:

这是一个data.table 选项

setDT(df)[, .SD[which.max(rowSums(.SD != 0))], ID]

给了

   ID X Y R Z
1:  1 0 2 0 1
2:  2 1 0 0 1
3:  3 1 1 1 1
4:  4 0 1 1 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 2017-11-11
    • 2022-01-01
    相关资源
    最近更新 更多