0

我的数据集看起来像这样:

df <- data.frame(compound = c("alanine ", "arginine", "asparagine", "aspartate"))
df <- matrix(rnorm(12*4), ncol = 12)
colnames(df) <- c("AC-1", "AC-2", "AC-3", "AM-1", "AM-2", "AM-3", "SC-1", "SC-2", "SC-3", "SM-1", "SM-2", "SM-3")
df <- data.frame(compound = c("alanine ", "arginine", "asparagine", "aspartate"), df)
 df
compound        AC.1        AC.2       AC.3       AM.1       AM.2            AM.3       SC.1       SC.2       SC.3         SM.1
1   alanine   1.18362683 -2.03779314 -0.7217692 -1.7569264 -0.8381042      0.06866567  0.2327702 -1.1558879  1.2077454  0.437707310
2   arginine -0.19610110  0.05361113  0.6478384 -0.1768597  0.5905398     -0.67945600 -0.2221109  1.4032349  0.2387620  0.598236199
3 asparagine  0.02540509  0.47880021 -0.1395198  0.8394257  1.9046667      0.31175358 -0.5626059  0.3596091 -1.0963363 -1.004673116
4  aspartate -1.36397906  0.91380826  2.0630076 -0.6817453 -0.2713498     -2.01074098  1.4619707 -0.7257269  0.2851122 -0.007027878

我想对列 [2:4] 和 [5:7] 列上的每一行(复合)执行 t 检验,并存储所有 p 值。基本上看每个化合物的AC组和AM组是否有区别。

我知道还有另一个主题,但是我找不到解决我的问题的可行解决方案。

PS。我的真实数据集大约有 35000 行(也许它需要一个与只有 4 行不同的解决方案)

4

2 回答 2

1

选择感兴趣的列后,通过选择前 3 个和后 3 个观察值作为输入并将提取的“p 值”作为原始数据中的另一列,pmap用于在每一行上应用t.testt.testbind

library(tidyverse)
df %>% 
  select(AC.1:AM.3) %>%
  pmap_dbl(~ c(...) %>%
               {t.test(.[1:3], .[4:6])$p.value}) %>% 
  bind_cols(df, pval_AC_AM = .)

或选择列后,执行gather转换为“长”格式spread,应用t.testinsummarise并与原始数据连接

df %>%
  select(compound, AC.1:AM.3) %>% 
  gather(key, val, -compound) %>% 
  separate(key, into = c('key1', 'key2')) %>%
  spread(key1, val) %>% 
  group_by(compound) %>%
  summarise(pval_AC_AM = t.test(AC, AM)$p.value) %>% 
  right_join(df)

更新

如果存在只有唯一值的情况,则t.test显示错误。一种选择是t.test针对这些情况运行并获取 NA。这可以通过possibly

posttest <- possibly(function(x, y) t.test(x, y)$p.value, otherwise = NA)
df %>% 
  select(AC.1:AM.3) %>%
  pmap_dbl(~ c(...) %>%
               {posttest(.[1:3], .[4:6])}) %>% 
  bind_cols(df, pval_AC_AM = .)

posttest(rep(3,5), rep(1, 5))
#[1] NA
于 2018-07-05T16:59:21.490 回答
0

如果您可以使用外部库:

library(matrixTests)

row_t_welch(df[,2:4], df[,5:7])$pvalue
[1] 0.67667626 0.39501003 0.26678161 0.01237438
于 2022-01-08T09:32:46.240 回答