【问题标题】:Matching values based on group ID根据组 ID 匹配值
【发布时间】:2015-07-03 00:53:21
【问题描述】:

假设我有以下数据框(实际的代表非常大的数据集)

df<- structure(list(x = c(1, 1, 1, 2, 2, 3, 3, 3), y = structure(c(1L, 
6L, NA, 2L, 4L, 3L, 7L, 5L), .Label = c("all", "fall", "hello", 
"hi", "me", "non", "you"), class = "factor"), z = structure(c(5L, 
NA, 4L, 2L, 1L, 6L, 3L, 4L), .Label = c("fall", "hi", "me", "mom", 
"non", "you"), class = "factor")), .Names = c("x", "y", "z"), row.names = c(NA, 
-8L), class = "data.frame")

看起来像

>df
  x     y    z
1 1   all  non
2 1   non <NA>
3 1  <NA>  mom
4 2  fall   hi
5 2    hi fall
6 3 hello  you
7 3   you   me
8 3    me  mom

我要做的是计算每组x(1,2 或 3)中匹配值的数量。例如,组号1 有一个匹配值是"non"(NA 应该被忽略)。所需的输出如下所示:

  x    n
1 1    1
2 2    2
3 3    2

试图以某种方式思考而不是 for-loop,因为我有一个大型数据集但无法通过。

【问题讨论】:

    标签: r match


    【解决方案1】:

    使用dplyr:

    library(dplyr)
    
    df %>% group_by(x) %>%
           summarise(n = sum(y %in% na.omit(z)))
    

    【讨论】:

    • 不太清楚为什么它没有给我想要的输出。它给了我n 1 5
    • @AhmedSalhin 为我工作。也许plyr 正在干扰。我认为这些包有一些不兼容的地方,具体取决于它们的加载顺序。
    • @Frank 是的,你是对的。我分离了plyr,它对我有用。你知道如何克服干扰问题吗?
    • @AhmedSalhin 按plyrdplyr 的顺序加载,或者明确将summarisedplyr::summarise 一起使用
    • @LegalizeIt 我将在函数之前指定包,以防plyr中的另一个函数干扰dplyr
    【解决方案2】:

    只是为了夜间娱乐,我尝试了一个基本的 R 解决方案,这当然是丑陋的地狱。

    ind <- by(df, df$x, function(x) which(na.omit(x[["y"]]) %in% na.omit(df[["z"]])))
    sm <- lapply(ind, length)
    cbind(unique(df$x), sm)
    sm
    1 1 1 
    2 2 2 
    3 3 2 
    

    另一种基本 R 方法,代码更少(我希望丑陋更少):

    ind <- by(df, df$x, function(x) sum(na.omit(x[["y"]]) %in% na.omit(x[["z"]])))
    cbind(unique(df$x), ind)
        ind
    1 1   1
    2 2   2
    3 3   2
    

    【讨论】:

      【解决方案3】:

      这是使用by()match() 的解决方案:

      do.call(rbind,by(df,df$x,function(g) c(x=g$x[1],n=sum(!is.na(match(g$y,g$z,inc=NA))))));
      ##   x n
      ## 1 1 1
      ## 2 2 2
      ## 3 3 2
      

      【讨论】:

      • 我喜欢这个基本的 R 解决方案......老实说,我的更长而且笨拙,我更喜欢这个。投票!
      猜你喜欢
      • 2019-01-27
      • 1970-01-01
      • 2021-10-04
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 2019-12-01
      • 1970-01-01
      • 2016-11-18
      相关资源
      最近更新 更多