【问题标题】:using aggregate in R when returning matrix返回矩阵时在R中使用聚合
【发布时间】:2014-11-24 23:41:13
【问题描述】:

我想使用聚合对一组矩阵进行一些操作,这些矩阵按customer_id 分组,这是我的数据框df 的一列。

例如,我想取df 对应不同customer_id 的子集,并在这些子集中添加一些列,然后全部返回。

在 Python 中,我会使用 groupby 并应用。

如何在 R 中做到这一点?

我写的代码是这样的:

gr_TILPS = aggregate(df,by=list(df[,"customer_id"]),FUN=kmeansfunction)

Error in TILPSgroup$hour : $ operator is invalid for atomic vectors

错误来自我猜的 kmeansfunction,它看起来像:

kmeansfunction = function(dfgroup){

Hour =dfgroup$hour
Weekday =TILPSgroup$WeekdayPrime
x <- cbind(Hour, Weekday)
colnames(x) <- c("x", "y")
(cl <- kmeans(x, 2))
clusters = cl$cluster
origclusters = as.factor(clusters)
dfgroup = cbind(dfgroup,origclusters)

return(dfgroup) 

}

【问题讨论】:

    标签: python r function matrix apply


    【解决方案1】:

    aggregate 将相同的函数应用于多个单个列。如果您想处理列的集合,请使用此范例:lapply(split(df,group),function);

    试试这个:

    gr_TILPS <- lapply( split(df, df[,"customer_id"]),
                        FUN=kmeansfunction)
    

    听起来像 python 可能与实验包有一些相似之处:'dplyr'。从某种意义上说,aggregate 只是块内的面向列的处理策略,而当您对由阻塞标准定义的整行数据感兴趣时,lapply(split, ), ) 策略更适用。如果您以后想将这些结果重新绑定在一起,您可以随时使用do.call(rbind, res_from_lapply)

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 1970-01-01
      • 2015-03-24
      • 1970-01-01
      • 2020-09-04
      • 2014-12-29
      • 1970-01-01
      • 2017-12-14
      • 1970-01-01
      相关资源
      最近更新 更多