我将(x, y)
值存储在数据帧中.我想返回最常出现的(x, y)
组合.
这是一个例子:
> x = c(1, 1, 2, 3, 4, 5, 6)
> y = c(1, 1, 5, 6, 9, 10, 12)
> xy = data.frame(x, y)
> xy
x y
1 1 1
2 1 1
3 2 5
4 3 6
5 4 9
6 5 10
7 6 12
Run Code Online (Sandbox Code Playgroud)
最常见的(x, y)
价值是(1, 1)
.
我在这里尝试了一个专栏的答案.它适用于单个列,但不适用于两列的聚合.
> tail(names(sort(table(xy$x))), 1)
[1] "1"
> tail(names(sort(table(xy$x, xy$y))), 1)
NULL
Run Code Online (Sandbox Code Playgroud)
如何在R中的数据框中的两列中检索最重复的(x,y)值?
编辑:c(1, 2)
应该被认为是不同的c(2, 1)
.
Dav*_*urg 11
不确定所需的输出应该如何,但这是一个可能的解决方案
res <- table(do.call(paste, xy))
res[which.max(res)]
# 1 1
# 2
Run Code Online (Sandbox Code Playgroud)
为了获得实际值,人们可以做到
res <- do.call(paste, xy)
xy[which.max(ave(seq(res), res, FUN = length)), ]
# x y
# 1 1 1
Run Code Online (Sandbox Code Playgroud)
(尽管所有的加票都是@DavidArenburg和我的方法的混合体
res = do.call("paste", c(xy, sep="\r"))
which.max(tabulate(match(res, res)))
Run Code Online (Sandbox Code Playgroud)
可能简单有效.)
也许它似乎有点圆,但第一步是将列中的可能任意值转换xy
为整数,范围从1到列中唯一值的数量
x = match(xy[[1]], unique(xy[[1]]))
y = match(xy[[2]], unique(xy[[2]]))
Run Code Online (Sandbox Code Playgroud)
然后将列组合编码为唯一值
v = x + (max(x) - 1L) * y
Run Code Online (Sandbox Code Playgroud)
索引最小化了所考虑的值的范围,并且编码将二维问题简化为单个维度.这些步骤将任何制表所需的空间(与table()
其他答案一样)减少到最小,而不创建字符向量.
如果想要在一个维度中最常见,那么可以索引和制表 v
tbl = tabulate(match(v, v))
Run Code Online (Sandbox Code Playgroud)
并找到第一次出现的最大值的索引,例如,
df[which.max(tbl),]
Run Code Online (Sandbox Code Playgroud)
这是一个魔术的功能
whichpairmax <- function(x, y) {
x = match(x, unique(x)); y = match(y, unique(y))
v = x + (max(x) - 1L) * y
which.max(tabulate(match(v, v)))
}
Run Code Online (Sandbox Code Playgroud)
和几个测试
> set.seed(123)
> xy[whichpairmax(xy[[1]], xy[[2]]),]
x y
1 1 1
> xy1 = xy[sample(nrow(xy)),]
> xy1[whichpairmax(xy1[[1]], xy1[[2]]),]
x y
1 1 1
> xy1
x y
3 2 5
5 4 9
7 6 12
4 3 6
6 5 10
1 1 1
2 1 1
Run Code Online (Sandbox Code Playgroud)
对于任意data.frame
whichdfmax <- function(df) {
v = integer(nrow(df))
for (col in df) {
col = match(col, unique(col))
v = col + (max(col) - 1L) * match(v, unique(v))
}
which.max(tabulate(match(v, v)))
}
Run Code Online (Sandbox Code Playgroud)
尝试
library(data.table)
setDT(xy)[, .N,list(x,y)][which.max(N)]
# x y N
#1: 1 1 2
Run Code Online (Sandbox Code Playgroud)