r - R 为每行运行 T 检验/方差分析,每行有 2 组,有 3 个样本
问题描述
我的数据集看起来像这样:
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 行不同的解决方案)
解决方案
选择感兴趣的列后,通过选择前 3 个和后 3 个观察值作为输入并将提取的“p 值”作为原始数据中的另一列,pmap
用于在每一行上应用t.test
t.test
bind
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.test
insummarise
并与原始数据连接
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
推荐阅读
- python - django查询很慢,但是我的sql查询很快
- php - 修剪功能不适用于字符串数组
- python - 在 pipenv shell 中运行“pipenv install”
- android - 将 targetSDK 设置为 API 30 后,我的 Android 应用程序无法正常工作;我如何找出原因?
- kotlin - Kotlin 每 1 秒更新一次 textview
- reactjs - React 从我的 div 中删除密钥,然后因此引发错误
- c++ - SwapChain 图像转换障碍的问题
- microsoft-graph-api - Blazor Server Web 应用程序在访问日历资源时*仅**登录到 Graph
- r - 在 R 中计算具有两个特定条件的事件
- google-apps-script - 使用 Google App Scripts 在电子邮件中附加 Google Docs 文件