Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.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
Python 返回矩阵时在R中使用聚合_Python_R_Function_Matrix_Apply - Fatal编程技术网

Python 返回矩阵时在R中使用聚合

Python 返回矩阵时在R中使用聚合,python,r,function,matrix,apply,Python,R,Function,Matrix,Apply,我想使用aggregate对一组矩阵应用一些操作,这些矩阵按customer\u id分组,这是我的数据帧df的一列 例如,我想获取对应于不同客户id的df的子集,并向这些子集添加一些列,然后将它们全部返回 在Python中,我将使用groupby和apply 我在R怎么做 我编写的代码如下所示: gr_TILPS = aggregate(df,by=list(df[,"customer_id"]),FUN=kmeansfunction) Error in TILPSgroup$hour :

我想使用aggregate对一组矩阵应用一些操作,这些矩阵按
customer\u id
分组,这是我的数据帧
df
的一列

例如,我想获取对应于不同
客户id
df
的子集,并向这些子集添加一些列,然后将它们全部返回

在Python中,我将使用groupby和apply

我在R怎么做

我编写的代码如下所示:

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

Error in TILPSgroup$hour : $ operator is invalid for atomic vectors
我猜错误来自Kmeans函数,它看起来像:

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) 
kmeansfunction=函数(dfgroup){
小时=dfgroup$Hour
Weekday=TILPSgroup$WeekdayPrime

x
aggregate
将相同的函数应用于多个单列。如果您想处理列集合,请使用以下范例:
lappy(拆分(df,组),函数)

试试这个:

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