我想在不使用SQL的情况下在R中解决此问题。在数据框中查找行,最大值按另一列中的值分组
How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
当然,我可以用sqldf做到这一点,但必须有一个很酷的应用方法R中做到这一点,太?
我想在不使用SQL的情况下在R中解决此问题。在数据框中查找行,最大值按另一列中的值分组
How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
当然,我可以用sqldf做到这一点,但必须有一个很酷的应用方法R中做到这一点,太?
设置数据首先读取的数据:
Lines <- "id home datetime player resource
1 10 04/03/2009 john 399
2 11 04/03/2009 juliet 244
5 12 04/03/2009 borat 555
3 10 03/03/2009 john 300
4 11 03/03/2009 juliet 200
6 12 03/03/2009 borat 500
7 13 24/12/2008 borat 600
8 13 01/01/2009 borat 700
"
DF <- read.table(text = Lines, header = TRUE)
DF$datetime <- as.Date(DF$datetime, format = "%d/%m/%Y")
1)基地 - 由有许多方法来处理这个使用各种软件包,但在这里,我们首先会显示一个基础的解决方案:
> do.call("rbind", by(DF, DF$home, function(x) x[which.max(x$datetime), ]))
id home datetime player resource
10 1 10 2009-03-04 john 399
11 2 11 2009-03-04 juliet 244
12 5 12 2009-03-04 borat 555
13 8 13 2009-01-01 borat 700
1a)的基极 - AVE和的变化(也仅使用R的碱):
FUN <- function(x) which.max(x) == seq_along(x)
is.max <- ave(xtfrm(DF$datetime), DF$home, FUN = FUN) == 1
DF[is.max, ]
2)sqldf,在这里它使用sqldf以防万一:
> library(sqldf)
> sqldf("select id, home, max(datetime) datetime, player, resource
+ from DF
+ group by home")
id home datetime player resource
1 1 10 2009-03-04 john 399
2 2 11 2009-03-04 juliet 244
3 5 12 2009-03-04 borat 555
4 8 13 2009-01-01 borat 700
我不使用SQL一样,所以我会做这种方式。
1)
df <- read.table("your file", "your options") # I leave this to you
2)
row_with_max_value <- max(which(df$values & df$group_column=="desired_group"))
“row_with_max_value” 内容数据帧(DF)的行号,在其中找到的列的最大值 “的值” (df $值)按“group_column”分组。 如果“group_column”不是字符类型,请删除引号并使用相应的文本格式。
如果您需要的值,比
df$values[row_with_max_value]
也许这不是最优雅的方式,但你并不需要SQL,它工作(至少对我来说)
我不知道什么是“独特的”,但是'x [which.max(x $ var),]'做了另一部分。 – Frank
酷 - 谢谢!我从未使用过which.max。太好了! – Don