我在R中有345行和237列的以下数据框:
snp1 snp2 snp3 ... snp237
0 1 2 ... 0
0 1 1 ... 1
1 1 2 ... 2
1 0 0 ... 0
... ... ... ...
2 2 1 ... 0
我想在每一列中应用以下函数:
D=(number of 0)/(number of rows)
H=(number of 1)/(number of rows)
R=(number of 2)/(number of rows)
p=D+(0.5*H)
q=R+(0.5*H)
最后,我想在向量中存储每个snp的“p”和“q”。这个函数在R的单个命令中为每个snp计算“p”和“q”。有可能吗?
输出是:
snp1 snp2 snp3 ... snp237
p1 p2 p3 ... ... p237
q1 q2 q3 ... ... q237
提前致谢。
#DATA
set.seed(42)
d = data.frame(snp1 = sample(0:2, 10, TRUE),
snp2 = sample(0:2, 10, TRUE),
snp3 = sample(0:2, 10, TRUE))
#Function
foo = function(x){
len = length(x)
D = sum(x == 0)/len
H = sum(x == 1)/len
R = sum(x == 2)/len
p = D + 0.5 * H
q = R + 0.5 * H
return(c(p = p, q = q))
}
#Run foo for each column
sapply(d, foo)
# snp1 snp2 snp3
#p 0.35 0.4 0.35
#q 0.65 0.6 0.65
这是tidyverse
的一个选项。根据OP代码中的逻辑创建一个函数(f1
),返回长度为2的list
,然后在summarise_all
中使用该函数在每个数据列列上应用该函数
library(dplyr)
library(tidyr)
f1 <- function(x) {
H <- 0.5 * mean(x == 1)
list(list(p = mean(x == 0) + H,
q = mean(x == 2) + H))
}
df1 %>%
summarise_all(f1) %>%
unnest
# snp1 snp2 snp3
#1 0.75 0.625 0.375
#2 0.25 0.375 0.625
df1 <- structure(list(snp1 = c(0L, 0L, 1L, 1L), snp2 = c(1L, 1L, 1L,
0L), snp3 = c(2L, 1L, 2L, 0L)), class = "data.frame", row.names = c(NA,
-4L))