[英]How to apply a function in each column of a data frame?
我在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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.