创建一个变量,捕获按组最频繁出现的情况 [英] Create a variable capturing the most frequent occurence by group

查看:18
本文介绍了创建一个变量,捕获按组最频繁出现的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

定义:

df1 <-data.frame(
id=c(rep(1,3),rep(2,3)),
v1=as.character(c("a","b","b",rep("c",3)))
)

s.t.

> df1
  id v1
1  1  a
2  1  b
3  1  b
4  2  c
5  2  c
6  2  c

我想创建第三个变量 freq,它包含 v1 中最频繁的观察,通过 id s.t.

I want to create a third variable freq that contains the most frequent observation in v1 by id s.t.

> df2
  id v1 freq
1  1  a    b
2  1  b    b
3  1  b    b
4  2  c    c
5  2  c    c
6  2  c    c

推荐答案

您可以使用 ddply 和一个自定义函数来选择最频繁的值:

You can do this using ddply and a custom function to pick out the most frequent value:

myFun <- function(x){
    tbl <- table(x$v1)
    x$freq <- rep(names(tbl)[which.max(tbl)],nrow(x))
    x
}

ddply(df1,.(id),.fun=myFun)

注意 which.max 将返回最大值的第一次出现,在平局的情况下.请参阅 nnet 包中的 ??which.is.max 以获取随机断开连接的选项.

Note that which.max will return the first occurrence of the maximum value, in the case of ties. See ??which.is.max in the nnet package for an option that breaks ties randomly.

这篇关于创建一个变量,捕获按组最频繁出现的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆