【问题标题】:How to find rows in a dataframe that show unique results across multiple columns如何在数据框中查找跨多列显示唯一结果的行
【发布时间】:2021-12-21 18:02:22
【问题描述】:

这可能是一个简单的答案,但我在寻找此解决方案时遇到问题,请寻求帮助。

> fruit.names <- c(rep("apple",3), rep("pear",3), rep("pepper", 3), rep("rice",3))
> adj <- c(rep("red", 3), rep("not round", 2), "yellow", rep("hot", 3), "grain", "white", "starch")
> df.start <- data.frame(fruit.names, adj)
> df.start
   fruit.names       adj
1        apple       red
2        apple       red
3        apple       red
4         pear not round
5         pear not round
6         pear    yellow
7       pepper       hot
8       pepper       hot
9       pepper       hot
10        rice     grain
11        rice     white
12        rice    starch

我需要只列出唯一的 df.start$names 的代码,并且对于 df.start$names 中的每个项目在 df.start$adj 中具有所有 same 结果。

所以结果应该是这样的。如果可能的话,我宁愿只使用基础 R(即没有 tidyr/dplyr。)

> df.results
 fruit.names     adj
1   apple        red
2   pepper       hot

【问题讨论】:

    标签: r dataframe sorting


    【解决方案1】:

    几种方法:

    基础 R

    ind <- ave(df.start$adj, df.start$fruit.names, FUN = function(z) length(unique(z)) == 1) == "TRUE"
    unique(df.start[ind,])
    #   fruit.names adj
    # 1       apple red
    # 7      pepper hot
    

    需要对照字符串检查"TRUE"是因为ave要求它的返回值和输入向量是同一个类,所以输出是强制的。

    dplyr

    (为人群提供,虽然我知道你说过你更喜欢基础 R。)

    library(dplyr)
    df.start %>%
      group_by(fruit.names) %>%
      filter(length(unique(adj)) == 1) %>%
      ungroup() %>%
      distinct()
    # # A tibble: 2 x 2
    #   fruit.names adj  
    #   <chr>       <chr>
    # 1 apple       red  
    # 2 pepper      hot  
    

    【讨论】:

    • @r2evens 谢谢!我假设 ave() 解决方案也适用于第三列?
    • 如果第三列是另一个分组列,那么您可以将它添加到第二个参数中,如df.start[,c("fruit.names","othercol")]。但是如果你有(比如)adj2(另一个需要唯一性的列),那么使用ave 可能需要更多技巧。
    猜你喜欢
    • 2020-03-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    相关资源
    最近更新 更多