我在我的代码中使用colSums但我还需要总和旁边的标准偏差.我在互联网上搜索,发现这个页面只包含:
colSums
colMeans
Run Code Online (Sandbox Code Playgroud)
http://stat.ethz.ch/R-manual/R-devel/library/base/html/colSums.html
我试过这个:
colSd
Run Code Online (Sandbox Code Playgroud)
但是我收到了这个错误:
Error: could not find function "colSd"
Run Code Online (Sandbox Code Playgroud)
我如何做同样的事情,但标准偏差:
colSd
Run Code Online (Sandbox Code Playgroud)
这是代码:
results <- colSums(x,na.rm=TRUE)#### here I want colsd
Run Code Online (Sandbox Code Playgroud) 我想计算矩阵中每行的方差.对于以下矩阵A
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 5 6 10
[3,] 50 7 11
[4,] 4 8 12
Run Code Online (Sandbox Code Playgroud)
我想得到
[1] 16.0000 7.0000 564.3333 16.0000
Run Code Online (Sandbox Code Playgroud)
我知道我可以实现这一目标apply(A,1,var),但是有更快或更好的方法吗?从八度,我可以这样做var(A,0,2),但我不知道如何使用R Y中的var()函数的参数.
编辑:典型块的实际数据集大约有100行和500列.但总数据量约为50GB.
我试图使用data.table执行一个简单的总和和行的意思,但我得到了意想不到的结果.我按照FAQ.table 的FAQ手册第2节的帮助.我发现了一种有效的方法,但我不确定为什么常见问题解答第2节中的这种方法不适用.这个方法给了我不正确的结果(即,它给了我第一列的值):
dt[, genesum:=lapply(.SD,sum), by=gene]
head(dt)
gene TCGA_04_1348 TCGA_04_1362 genesum
1: A1BG 0.94565 0.70585 0.94565
2: A1BG-AS 0.97610 1.15850 0.97610
3: A1CF 0.00000 0.02105 0.00000
4: A2BP1 0.00300 0.04150 0.00300
5: A2LD1 4.57975 5.02820 4.57975
6: A2M 60.37320 36.09715 60.37320
Run Code Online (Sandbox Code Playgroud)
这给了我想要的结果
dt[, genesum:=apply(dt[,-1, with=FALSE],1, sum)]
head(dt)
gene TCGA_04_1348 TCGA_04_1362 genesum
1: A1BG 0.94565 0.70585 1.65150
2: A1BG-AS 0.97610 1.15850 2.13460
3: A1CF 0.00000 0.02105 0.02105
4: A2BP1 0.00300 0.04150 0.04450
5: A2LD1 4.57975 5.02820 …Run Code Online (Sandbox Code Playgroud) 以下代码是否表示遍历 R 的行data.table并将在每一行找到的值传递给函数的首选过程?或者有没有更高效的方法来做到这一点?
library(data.table)
set.seed(2)
n <- 100
b <- c(0.5, 1.5, -1)
phi <- 0.8
X <- cbind(1, matrix(rnorm(n*2, 0, 1), ncol = 2))
y <- X %*% matrix(b, ncol = 1) + rnorm(n, 0, phi)
d <- data.table(y, X)
setnames(d, c("y", "x0", "x1", "x2"))
logpost <- function(d, b1, b2, b3, phi, mub = 1, taub = 10, a = 0.5, z = 0.7){
N <- nrow(d)
mu <- b1 + b2 * d$x1 + b3 * …Run Code Online (Sandbox Code Playgroud) 与数据帧相比,我对tapply使用类似操作的速度有多大提高,我印象非常深刻data.table.
例如:
df = data.frame(class = round(runif(1e6,1,1000)), x=rnorm(1e6))
DT = data.table(df)
# takes ages if somefun is complex
res1 = tapply(df$x, df$class, somefun)
# takes much faster
setkey(DT, class)
res2 = DT[,somefun(x),by=class]
Run Code Online (Sandbox Code Playgroud)
但是,我并没有完全让它的工作速度明显快于apply类似数据帧的操作(即,需要将函数应用于每一行的情况).
df = data.frame(x1 = rnorm(1e6), x2=rnorm(1e6))
DT = data.table(df)
# takes ages if somefun is complex
res1 = apply(df, 1, somefun)
# not much improvement, if at all
DT[,rowid:=.I] # or: DT$rowid = 1:nrow(DT)
setkey(DT, rowid)
res2 = DT[,somefun1(x1,x2),by=rowid]
Run Code Online (Sandbox Code Playgroud)
这真的只是预期还是有一些技巧?