r - 如何 ddply() 不排序?

标签 r sorting plyr

我使用以下代码来总结我的数据,按化合物、重复和质量分组。

summaryDataFrame <- ddply(reviewDataFrame, .(Compound, Replicate, Mass), 
  .fun = calculate_T60_Over_T0_Ratio)

一个不幸的副作用是结果数据帧按这些字段排序。我想这样做并使复合、复制和质量保持与原始数据框中相同的顺序。有任何想法吗?我尝试向原始数据添加一个连续整数的“排序”列,但当然我不能将它包含在 .variables 中,因为我不想“分组”,所以它不会在摘要数据帧。

谢谢您的帮助。

最佳答案

这是在 plyr 上出现的不久前的邮件列表(由@kohske 提出),这是 Peter Meil​​strup 为有限情况提供的解决方案:

#Peter's version used a function gensym to
# create the col name, but I couldn't track down
# what package it was in.
keeping.order <- function(data, fn, ...) { 
  col <- ".sortColumn"
  data[,col] <- 1:nrow(data) 
  out <- fn(data, ...) 
  if (!col %in% colnames(out)) stop("Ordering column not preserved by function") 
  out <- out[order(out[,col]),] 
  out[,col] <- NULL 
  out 
} 

#Some sample data 
d <- structure(list(g = c(2L, 2L, 1L, 1L, 2L, 2L), v = c(-1.90127112738315, 
-1.20862680183042, -1.13913266070505, 0.14899803094742, -0.69427656843677, 
0.872558638137971)), .Names = c("g", "v"), row.names = c(NA, 
-6L), class = "data.frame") 

#This one resorts
ddply(d, .(g), mutate, v=scale(v)) #does not preserve order of d 

#This one does not
keeping.order(d, ddply, .(g), mutate, v=scale(v)) #preserves order of d 

请务必阅读 thread哈德利关于为什么这个功能可能不够通用,无法转入 ddply 的注释,特别是因为它可能适用于您的情况,因为您可能会在每件作品中返回较少的行。

编辑以包含更一般情况的策略

ddply正在输出按您不喜欢的顺序排序的内容,您基本上有两个选择:使用有序因子预先指定拆分变量的所需排序,或者事后手动对输出进行排序。

例如,考虑以下数据:
d <- data.frame(x1 = rep(letters[1:3],each = 5), 
                x2 = rep(letters[4:6],5),
                x3 = 1:15,stringsAsFactors = FALSE)

暂时使用字符串。 ddply将对输出进行排序,在这种情况下将需要默认的词法排序:
> ddply(d,.(x1,x2),summarise, val = sum(x3))
  x1 x2 val
1  a  d   5
2  a  e   7
3  a  f   3
4  b  d  17
5  b  e   8
6  b  f  15
7  c  d  13
8  c  e  25
9  c  f  27


> ddply(d[sample(1:15,15),],.(x1,x2),summarise, val = sum(x3))
  x1 x2 val
1  a  d   5
2  a  e   7
3  a  f   3
4  b  d  17
5  b  e   8
6  b  f  15
7  c  d  13
8  c  e  25
9  c  f  27

如果生成的数据框没有以“正确”的顺序结束,那可能是因为您确实希望其中一些变量成为有序因子。假设我们真的想要 x1x2像这样订购:
d$x1 <- factor(d$x1, levels = c('b','a','c'),ordered = TRUE)
d$x2 <- factor(d$x2, levels = c('d','f','e'), ordered = TRUE)

现在当我们使用 ddply ,结果排序将如我们所愿:
> ddply(d,.(x1,x2),summarise, val = sum(x3))
  x1 x2 val
1  b  d  17
2  b  f  15
3  b  e   8
4  a  d   5
5  a  f   3
6  a  e   7
7  c  d  13
8  c  f  27
9  c  e  25

这里故事的寓意是,如果 ddply正在以您不想要的顺序输出某些内容,这是一个好兆头,您应该对要拆分的变量使用有序因子。

关于r - 如何 ddply() 不排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7235421/

相关文章:

r - 我可以用更优雅的方式计算帐户余额吗

r - 在 Rcpp 中设置 *only* 列名

java - 搜索 ArrayList 中 Key 的总和 (Java)

php - 优化MYSQL+PHP父子输出

r - llply 在 Parallel - R 中失败

r - 在 R 中使用循环进行卡方检验

regex - 使用两个标准对 R 中的数据框进行子集化,其中之一是正则表达式

c - 在不使用文件的情况下对 C 中的队列中的数字进行排序

r - 将 n 个函数的列表应用于数据帧的每一行?

r - 构建均值/方差汇总表的快速/优雅方法