创建一个捕获最频繁出现的变量的变量

编程入门 行业动态 更新时间:2024-10-08 20:39:03
本文介绍了创建一个捕获最频繁出现的变量的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

定义:

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

st

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

我想创建一个第三个变量 freq 包含 v1 由 id st

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)

b $ b

请注意,如果是tie, 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.

更多推荐

创建一个捕获最频繁出现的变量的变量

本文发布于:2023-11-29 09:28:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646007.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   创建一个   频繁

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!