[英]R: loop performing ks tests across data frame stored in matrix
I apologize for strange syntax, I am just now learning to program. 我为奇怪的语法感到抱歉,我现在正在学习编程。 I have a df of 100 columns and 5304 rows. 我有100列和5304行的df。 I need to perform separate two sided ks.tests on 94 of those last numeric columns (6:ncol(df)) using the 5th numeric column or reference column: 我需要使用第5个数字列或引用列对94个最后的数字列(6:ncol(df))分别执行双面ks.test:
r<-df$rank.
I'd also like to store the pvalues in a matrix. 我也想将pvalues存储在一个矩阵中。 From what I understand, I can either use a 'for loop' or 'apply' functions. 据我了解,我可以使用“ for循环”或“应用”功能。 I have a simple code that only outputs a single stat summary (it seems like it is overwriting the results): 我有一个简单的代码,仅输出一个统计摘要(似乎正在覆盖结果):
for (i in 6:ncol(df))
y<-df[,i]
ks.test(r,y)->K
> K
Two-sample Kolmogorov-Smirnov test
data: r and y
D = 0.71983, p-value < 2.2e-16
alternative hypothesis: two-sided
I've tried many variations of this as well as using lapply wrong. 我已经尝试了许多变体以及错误地使用了lapply。 Any insight as to why "K" should not return multiple values or assigning the output to a matrix? 关于为什么“ K”不应返回多个值或将输出分配给矩阵的任何见解? Thank you. 谢谢。
edit: sample data set 编辑:样本数据集
probe set symbol zscore rank X1 X4 X13 X15 ....N (N=100)
22133-x_at SP110 4.73635 1 400 14 5 1000
. 2 5 430 56 150
. 3 24 78 23 9000
...N
(N=5304)
Consider sapply
to return a matrix of ks.test
statistic and p.value : 考虑sapply
返回的矩阵ks.test
统计和p.value:
# RANDOM DATA TO DEMONSTRATE
set.seed(147)
df <- data.frame(id1 = sample(LETTERS, 5304, replace=TRUE),
id2 = sample(LETTERS, 5304, replace=TRUE),
id3 = sample(LETTERS, 5304, replace=TRUE),
id4 = sample(LETTERS, 5304, replace=TRUE),
setNames(lapply(5:100, function(i) rnorm(5304)),
paste0("Col", 5:100)))
r <- df[,5]
res <- sapply(df[,6:100], function(y) {
ks <- ks.test(r, y)
c(statistic=ks$statistic, p.value=ks$p.value)
setNames(c(ks$statistic, ks$p.value), c("statistic", "p.value"))
})
# PRINT FIRST FIVE COLS
res[,1:5]
# Col6 Col7 Col8 Col9 Col10
# statistic 0.02111614 0.01338612 0.01074661 0.0224359 0.01677979
# p.value 0.18774138 0.72887906 0.91933648 0.1384762 0.44412866
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.