r - R:将行数据框中的值除以该行中的最大值
问题描述
我想在 R 中做一件简单的事情。我有一个包含 1000 行和几列的数据框,并且想将数据框中的每个值除以其相应行中的最大值。
数据框示例:
x <- data.frame("condition_1" = c(2,4,6,8,10), "condition_2" = c(1,4,5,3,2), "condition_3" = c(1,5,9,3,12))
row.names(x) <- c('gene_1', 'gene_2', 'gene_3', 'gene_4', 'gene_5')
数据框如下所示:
> x
condition_1 condition_2 condition_3
gene_1 2 1 1
gene_2 4 4 5
gene_3 6 5 9
gene_4 8 3 3
gene_5 10 2 12
现在,我用下面的代码解决了我的问题:
xnorm = NULL
for (row in 1:nrow(x)){
tmp = x[row,] / max(x[row,])
xnorm = rbind(xnorm, tmp)
}
rownames(xnorm) = rownames(x)
输出如下所示:
> xnorm
condition_1 condition_2 condition_3
gene_1 1.0000000 0.5000000 0.500
gene_2 0.8000000 0.8000000 1.000
gene_3 0.6666667 0.5555556 1.000
gene_4 1.0000000 0.3750000 0.375
gene_5 0.8333333 0.1666667 1.000
如您所见,这是可行的。但是,我的解决方案似乎太复杂了,我确信为此必须有一些干净的 R 解决方案。谁能指出我正确的方向以获得更好的解决方案?
解决方案
在base R
中,可以用vectorized
pmax
x/do.call(pmax, x)
-输出
# condition_1 condition_2 condition_3
#gene_1 1.0000000 0.5000000 0.500
#gene_2 0.8000000 0.8000000 1.000
#gene_3 0.6666667 0.5555556 1.000
#gene_4 1.0000000 0.3750000 0.375
#gene_5 0.8333333 0.1666667 1.000
或使用效率较低的方法apply
t(apply(x, 1, function(u) u/max(u)))
推荐阅读
- python - 在 Python 中更改逗号分隔的多行文本文件中的单个单词,而不使用 CSV 或映射
- c# - Wuapi.dll Search() 未返回所有更新
- oauth-2.0 - AuthO 博客中 WHATABYTE Dashboard 的 git repo 是什么
- cucumber - 如何使用 Cypress-tags 在 circle-ci orb 上运行 Cypress 测试
- c# - 裁剪圆角边框的内容,图像超出边框
- go - x509.DecryptPEMBlock 已弃用
- android - 在 Android 的 ScrollView 下方查看
- algorithm - 如何在字符串中查找句子中的单词数?
- microsoft-graph-api - 使用 mail.send 时的 Microsoft Graph OrganizationFromTenantGuidNotFound
- android - Gradle 更新时出错:预期 minSdkVersion >= 21 但找到 1