使用 R 计算比率矩阵
我想知道是否有一种简单的方法来计算数据框中每个元素的比率矩阵。示例 -
gene sample1 sample2 sample3 sample4 .....
aa 2 2 3 2
aa 1 5 2 1
aa 4 1 2 3
bb 1 2 1 2
bb 2 1 1 2
I 是为每列基因中的公共行值计算的从样本 1 到样本 4 的每个元素的比率。计算将是这样的 -
gene sample1 sample2 sample3 sample4 .....
aa 2/7 2/8 3/7 2/6
aa 1/7 5/8 2/7 1/6
aa 4/7 1/8 2/7 3/6
bb 1/3 2/3 1/2 2/4
bb 2/3 1/3 1/2 2/4
结果将是这样的 -
gene sample1 sample2 sample3 sample4 .....
aa .28 .25 .42 .33
aa .14 .62 .28 .16
aa .57 .12 .28 .5
bb .33 .66 .5 .5
bb .66 .33 .5 .5
我在循环中尝试过的是这样的 -
tf <- dd %>%
group_by(symbol) %>%
summarise_if(is.numeric, mean)
但这是总结但不计算每个元素并保持初始数据帧的相同矩阵维度(例如这里是 dd ) 。任何建议将不胜感激。
I was wondering if there is a simple method to calculate a ratio matrix for each element in a data frame. Example -
gene sample1 sample2 sample3 sample4 .....
aa 2 2 3 2
aa 1 5 2 1
aa 4 1 2 3
bb 1 2 1 2
bb 2 1 1 2
and I was the ratio for each element from sample1 to sample4 calculated for common row values in gene in each column. The calculation would be like this -
gene sample1 sample2 sample3 sample4 .....
aa 2/7 2/8 3/7 2/6
aa 1/7 5/8 2/7 1/6
aa 4/7 1/8 2/7 3/6
bb 1/3 2/3 1/2 2/4
bb 2/3 1/3 1/2 2/4
The result would be like this -
gene sample1 sample2 sample3 sample4 .....
aa .28 .25 .42 .33
aa .14 .62 .28 .16
aa .57 .12 .28 .5
bb .33 .66 .5 .5
bb .66 .33 .5 .5
What I have tried in a loop is this -
tf <- dd %>%
group_by(symbol) %>%
summarise_if(is.numeric, mean)
but this summarises but does not calculate for each element and keep the same matrix dimension of initial data frame (e.g here its dd). Any suggestion would be most appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以做:
如果您想忽略的缺少值,请使用:
数据:
You can do:
If you have missing values that you'd like to ignore, use:
Data:
这是
data.table
的一个选项Here is an option with
data.table