应用功能在列组应用功能在列组(apply a function over groups of col

2019-05-14 08:56发布

如何使用apply或相关的函数来创建一个包含一个非常大的数据帧每对列的行平均的结果,新的数据帧?

我有输出仪器n复制上的大量样品,其中每个单个的测量是一个矢量(所有测量都是相同长度的矢量)的测量。 我想上的所有复制的每个样品的测量结果计算平均(和其它数据)。 这意味着我需要组n连续列在一起,做逐行计算。

对于一个简单的例子,对两个样品三次重复测量,我怎样才能最终使用具有两列(每采样1)的数据帧,一个是平均的重复的每一行中dat$adat$bdat$c和一个是每行的平均dat$ddat$edat$f

下面是一些示例数据

dat <- data.frame( a = rnorm(16), b = rnorm(16), c = rnorm(16), d = rnorm(16), e = rnorm(16), f = rnorm(16))

            a          b            c          d           e          f
1  -0.9089594 -0.8144765  0.872691548  0.4051094 -0.09705234 -1.5100709
2   0.7993102  0.3243804  0.394560355  0.6646588  0.91033497  2.2504104
3   0.2963102 -0.2911078 -0.243723116  1.0661698 -0.89747522 -0.8455833
4  -0.4311512 -0.5997466 -0.545381175  0.3495578  0.38359390  0.4999425
5  -0.4955802  1.8949285 -0.266580411  1.2773987 -0.79373386 -1.8664651
6   1.0957793 -0.3326867 -1.116623982 -0.8584253  0.83704172  1.8368212
7  -0.2529444  0.5792413 -0.001950741  0.2661068  1.17515099  0.4875377
8   1.2560402  0.1354533  1.440160168 -2.1295397  2.05025701  1.0377283
9   0.8123061  0.4453768  1.598246016  0.7146553 -1.09476532  0.0600665
10  0.1084029 -0.4934862 -0.584671816 -0.8096653  1.54466019 -1.8117459
11 -0.8152812  0.9494620  0.100909570  1.5944528  1.56724269  0.6839954
12  0.3130357  2.6245864  1.750448404 -0.7494403  1.06055267  1.0358267
13  1.1976817 -1.2110708  0.719397607 -0.2690107  0.83364274 -0.6895936
14 -2.1860098 -0.8488031 -0.302743475 -0.7348443  0.34302096 -0.8024803
15  0.2361756  0.6773727  1.279737692  0.8742478 -0.03064782 -0.4874172
16 -1.5634527 -0.8276335  0.753090683  2.0394865  0.79006103  0.5704210

我这样的事情后,我

            X1          X2
1  -0.28358147 -0.40067128
2   0.50608365  1.27513471
3  -0.07950691 -0.22562957
4  -0.52542633  0.41103139
5   0.37758930 -0.46093340
6  -0.11784382  0.60514586
7   0.10811540  0.64293184
8   0.94388455  0.31948189
9   0.95197629 -0.10668118
10 -0.32325169 -0.35891702
11  0.07836345  1.28189698
12  1.56269017  0.44897971
13  0.23533617 -0.04165384
14 -1.11251880 -0.39810121
15  0.73109533  0.11872758
16 -0.54599850  1.13332286

我做到了这一点,但显然没有对我的更大的数据帧...

data.frame(cbind(
apply(cbind(dat$a, dat$b, dat$c), 1, mean),
apply(cbind(dat$d, dat$e, dat$f), 1, mean)
))

我试过apply和循环并不能完全得到它在一起。 我的实际数据有一定的几百列。

Answer 1:

这可能是更推广到您的情况,你通过索引列表。 如果速度是一个问题(大数据帧)我会选择lapplydo.call而非sapply

x <- list(1:3, 4:6)
do.call(cbind, lapply(x, function(i) rowMeans(dat[, i])))

工作,如果你只是山坳名字太:

x <- list(c('a','b','c'), c('d', 'e', 'f'))
do.call(cbind, lapply(x, function(i) rowMeans(dat[, i])))

编辑

正好想也许你想自动完成这个每三列做。 我知道有一个更好的办法,但在这里它是一个100列数据集:

dat <- data.frame(matrix(rnorm(16*100), ncol=100))

n <- 1:ncol(dat)
ind <- matrix(c(n, rep(NA, 3 - ncol(dat)%%3)), byrow=TRUE, ncol=3)
ind <- data.frame(t(na.omit(ind)))
do.call(cbind, lapply(ind, function(i) rowMeans(dat[, i])))

编辑2仍然不愉快的索引。 我认为有通过索引更好/更快的方式。 这里的第二个虽然没有满足的方法:

n <- 1:ncol(dat)
ind <- data.frame(matrix(c(n, rep(NA, 3 - ncol(dat)%%3)), byrow=F, nrow=3))
nonna <- sapply(ind, function(x) all(!is.na(x)))
ind <- ind[, nonna]

do.call(cbind, lapply(ind, function(i)rowMeans(dat[, i])))


Answer 2:

意味着从行矢量a,B,C

 rowMeans(dat[1:3])

装置,用于从向量d,E,F的行

 rowMeans(dat[4:6])

所有在一个呼叫你

results<-cbind(rowMeans(dat[1:3]),rowMeans(dat[4:6]))

如果你只知道列,而不是命令的名字,那么你可以使用:

rowMeans(cbind(dat["a"],dat["b"],dat["c"]))
rowMeans(cbind(dat["d"],dat["e"],dat["f"]))

#I dont know how much damage this does to speed but should still be quick


Answer 3:

类似的问题在这里提出由@大卫: R中的每个16列平均 (现已关闭),我回答了适应@ TylerRinker的回答以上,继@joran和@Ben建议。 因为得到的功能也许是帮助到OP或未来的读者,我在这里复制该功能,与OP的数据为例一起。

# Function to apply 'fun' to object 'x' over every 'by' columns
# Alternatively, 'by' may be a vector of groups
byapply <- function(x, by, fun, ...)
{
    # Create index list
    if (length(by) == 1)
    {
        nc <- ncol(x)
        split.index <- rep(1:ceiling(nc / by), each = by, length.out = nc)
    } else # 'by' is a vector of groups
    {
        nc <- length(by)
        split.index <- by
    }
    index.list <- split(seq(from = 1, to = nc), split.index)

    # Pass index list to fun using sapply() and return object
    sapply(index.list, function(i)
            {
                do.call(fun, list(x[, i], ...))
            })
}

然后,找到重复的平均值:

byapply(dat, 3, rowMeans)

或者,也许是重复的标准偏差:

byapply(dat, 3, apply, 1, sd)

更新

by也被指定为组的矢量:

byapply(dat, c(1,1,1,2,2,2), rowMeans)


Answer 4:

rowMeans解决方案会更快,但为了完整性这里是你如何可能做到这一点与apply

t(apply(dat,1,function(x){ c(mean(x[1:3]),mean(x[4:6])) }))


Answer 5:

通过@ joran的建议启发我想出了这个(从他的提议实际上是一个有点不同,虽然变调建议是特别有用):

例如做数据的数据帧与p的cols以模拟真实的数据集(以下@ TylerRinker的回答上面的,不像我在这个问题的坏榜样)

p <- 99 # how many columns?
dat <- data.frame(matrix(rnorm(4*p), ncol = p))

重命名这个数据帧列创建的组n连续列,所以,如果我感兴趣的三列的群体我得到这样的1,1,1,2,2,2,3,3,3列名等或者如果我想四列的群体将是1,1,1,1,2,2,2,2,3,3,3,3,等我有三个打算,现在(我猜这是一种索引为我这样的人谁不知道很多关于索引)

n <- 3 # how many consecutive columns in the groups of interest?
names(dat) <- rep(seq(1:(ncol(dat)/n)), each = n, len = (ncol(dat)))

现在使用申请和tapply得到一行意味着每个组的

dat.avs <- data.frame(t(apply(dat, 1, tapply, names(dat), mean)))

其主要缺点是在原始数据的列名被替换(尽管这可以通过将组号码一个新行,而不是colnames克服)和列名是由应用-tapply功能无益返回订购。

继@ joran的建议,这里有一个data.table的解决方案:

p <- 99 # how many columns?
dat <- data.frame(matrix(rnorm(4*p), ncol = p))
dat.t <-  data.frame(t(dat))

n <- 3 # how many consecutive columns in the groups of interest?
dat.t$groups <- as.character(rep(seq(1:(ncol(dat)/n)), each = n, len = (ncol(dat))))

library(data.table)
DT <- data.table(dat.t)
setkey(DT, groups)
dat.av <- DT[, lapply(.SD,mean), by=groups]

谢谢大家对你的快速和耐心的努力!



Answer 6:

还有,如果你有兴趣申请一个函数列的每个唯一组合,在什么被称为组合数学精美的简单的解决方案。

combinations <- combn(colnames(df),2,function(x) rowMeans(df[x]))

为了计算统计三列等的每一个唯一组合,只需改变2到3的操作被矢量和因此比循环,如更快的apply上面使用家庭功能。 如果列事项的顺序,那么你需要,而不是旨在重现有序集置换算法: combinat::permn



文章来源: apply a function over groups of columns