将基于列索引的函数应用于数据框

时间:2013-07-01 13:00:57

标签: r plyr

我正在尝试将某个函数应用于数据框中的列组,该数据框基于包含作为相同实验设计“组”的一部分的列索引的“设计”向量(即复制)。我的观察是行,我的采样点是列 设计向量指定哪些列应该组合在一起:

designvector <- c(rep(1,2), rep(2,3), rep(3,3), rep(4,2), rep(5,2), rep(6,2), 
                       rep(7,2), rep(8,2), rep(9,2))

我想要应用该功能的数据框的一个小例子是:

structure(list(`1` = c(4381L, 608L, 7648L, 458L, 350L, 203L), 
`1` = c(6450L, 1389L, 4896L, 526L, 920L, 352L), `2` = c(1966L, 
59L, 492L, 5291L, 1401L, 133L), `2` = c(6338L, 281L, 2649L, 
4718L, 1281L, 377L), `2` = c(12399L, 578L, 3094L, 1787L, 
1180L, 541L), `3` = c(9629L, 554L, 7299L, 2819L, 1314L, 497L
), `3` = c(11329L, 709L, 3720L, 2909L, 1929L, 655L), `3` = c(11319L, 
535L, 5212L, 2191L, 1239L, 633L), `4` = c(7427L, 8637L, 894L, 
2L, 782L, 120L), `4` = c(6748L, 9139L, 431L, 28L, 871L, 224L
), `5` = c(7125L, 11819L, 1728L, 9L, 607L, 313L), `5` = c(8651L, 
11022L, 442L, 96L, 728L, 249L), `6` = c(17879L, 3402L, 319L, 
6L, 1226L, 489L), `6` = c(20859L, 2648L, 463L, 10L, 1189L, 
408L), `7` = c(13457L, 1124L, 9386L, 18L, 635L, 367L), `7` = c(16292L, 
1732L, 6552L, 20L, 1022L, 431L), `8` = c(9035L, 5887L, 185L, 
11L, 550L, 1814L), `8` = c(14831L, 5833L, 570L, 8L, 1089L, 
1462L), `9` = c(22023L, 2254L, 5212L, 63L, 555L, 1254L), 
`9` = c(16887L, 2491L, 4949L, 68L, 921L, 983L)), .Names = c("1", 
"1", "2", "2", "2", "3", "3", "3", "4", "4", "5", "5", "6", "6", 
"7", "7", "8", "8", "9", "9"), row.names = c(NA, 6L), class = "data.frame")

然而,使用ddply我收到一个我不太懂的错误:  ddply(abmat.sum,.(designvector),mean)给出以下输出:

designvector V1
1            1 NA
2            2 NA
3            3 NA
4            4 NA
5            5 NA
6            6 NA
7            7 NA
8            8 NA
9            9 NA
Warning messages:
1: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
2: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
3: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
4: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
5: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
6: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
7: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
8: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA
9: In mean.default(piece, ...) :
  argument is not numeric or logical: returning NA

我对这里的错误一无所知。 任何使用ddply或其他方法然后在数据帧上循环的建议都是受欢迎的。

1 个答案:

答案 0 :(得分:1)

问题是abmat.sum形式错误(ddply要求“宽”而不是“长”)。使用melt来解决此问题。

library(reshape2)
abmat.sum_long <- melt(abmat.sum)
abmat.sum_long$variable <- as.numeric(abmat.sum_long$variable)

您还需要将summarise传递给ddply

library(plyr)
ddply(abmat.sum_long, .(variable), summarise, mean_value = mean(value))