R - 将函数参数转换为聚合函数

时间:2014-03-11 03:19:35

标签: r aggregate

我对R很新,所以请耐心等待。我创建了一个函数,并将参数传递给它。在函数中,我试图使用聚合函数并传递原始参数。

GetPlotFactors <- function(df, par1, par2) {
  index.value = match(par1,names(df))
  names(df)[index.value]
  headers = c(par1, 'A', 'B')
  sub <- subset(df, df[index.value] == par2, select = c(par1, 'A', 'B') )
  df.test <- aggregate(B~par1+A, FUN = 'sum', data = sub)

  Error in model.frame.default(formula = B ~ par1 + A, data = sub) : 
  variable lengths differ (found for 'par1') 

聚合函数似乎有问题,我不确定导致错误的原因。

dput(头(分)):

structure(list(Policy = structure(c(7L, 7L, 17L, 7L, 17L, 17L
 ), .Label = c("A", "B","C", "D", "E","F", "G", "H","I", "J", "K", 
"L", "M", "N","O", "P","R"), class = "factor"), A = structure(c(1L, 
1L, 1L, 1L, 1L, 1L), .Label = c("Rank_1", "Rank_2", "Rank_3", 
"Rank_4", "Rank_5", "Rank_6", "Rank_7", "Rank_8", "Rank_9", "Rank_10", 
"Rank_11", "Rank_12", "Rank_13", "Rank_14", "Rank_15", "Rank_16", 
"Rank_17", "Rank_18", "Rank_19", "Rank_20", "Rank_21", "Rank_22"),
, class = "factor"), 
B = c(0, 274.325, -809569.5495, -9534.5307, 15529.3678, 
-151893.0683)), .Names = c("Policy", "A", "B"), row.names = c(80L, 
100L, 145L, 172L, 201L, 203L), class = "data.frame")

0 个答案:

没有答案