Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
求系数的最大值,并在r中求最大值_R_Dataframe_Plyr - Fatal编程技术网

求系数的最大值,并在r中求最大值

求系数的最大值,并在r中求最大值,r,dataframe,plyr,R,Dataframe,Plyr,这应该是难以置信的简单,但我没有设法弄明白。我想得到每个组的最大值,我的操作如下 ddply(dd,~group,summarise,max=max(value)) 但除了返回值和组,我还想返回值、组和另一列date,索引如下(显然不起作用)。我该怎么做?谢谢 ddply(dd,~group,summarise,max=max(value))['date'] 如果您在与具有最大值的行相对应的日期之后,请尝试subset获取最大值的行以及选择获取您要查找的列 # reproducible

这应该是难以置信的简单,但我没有设法弄明白。我想得到每个组的最大值,我的操作如下

ddply(dd,~group,summarise,max=max(value))
但除了返回值和组,我还想返回值、组和另一列date,索引如下(显然不起作用)。我该怎么做?谢谢

ddply(dd,~group,summarise,max=max(value))['date']  

如果您在与具有最大值的行相对应的日期之后,请尝试
subset
获取最大值的行以及
选择
获取您要查找的列

# reproducible example using `iris`

# your original
ddply(iris, ~Species, summarise, max=max(Sepal.Length))
#      Species max
# 1     setosa 5.8
# 2 versicolor 7.0
# 3  virginica 7.9


# now we want to get the Sepal.Width that corresponds to max sepal.length too.
ddply(iris, ~Species, subset, Sepal.Length==max(Sepal.Length),
      select=c('Species', 'Sepal.Length', 'Sepal.Width'))
#      Species Sepal.Length Sepal.Width
# 1     setosa          5.8         4.0
# 2 versicolor          7.0         3.2
# 3  virginica          7.9         3.8
(或者不要在
子集中
调用中使用
选择
,只需在
ddply
后面使用
[,c('columns','I','want')]
)。如果同一物种有多行达到最大值,这将返回所有行

您也可以使用
summary
来执行此操作,只需在调用中添加您的
date
定义,但效率稍低(计算两次最大值):


这将只返回每个物种一行,如果有多朵花具有其物种的最大萼片长度,则只返回第一行(
which.max
返回第一个匹配索引)。

如果我们使用
data.table
(使用
iris
数据集),我们将data.frame转换为data.table,通过分组变量('Species')进行分组,我们得到一个变量('Sepal.Length')的
max
值的索引,并使用该索引对.SDcols中指示的列进行子集划分

library(data.table)
dt <- as.data.table(iris)
dt[, .SD[which.max(Sepal.Length)]  , by = Species, 
                 .SDcols= c('Sepal.Length', 'Sepal.Width')]
库(data.table)

dt工作得很好。感谢您提供的多种解决方案。作为将来的参考,这就是我最终选择的。ddply(dd,~group,subset,value==max(value),select=c('date2','value'))
library(data.table)
dt <- as.data.table(iris)
dt[, .SD[which.max(Sepal.Length)]  , by = Species, 
                 .SDcols= c('Sepal.Length', 'Sepal.Width')]