使用matrixStats :: rowMedians查找每行的中位数 [英] Find median of every row using matrixStats::rowMedians
问题描述
我正在尝试使用matrixStats
包中的rowMedians
计算数据帧df
的行中位数.
I am trying to calculate the row median for a data frame df
with rowMedians
from matrixStats
package.
Abundance Sample1 Sample2 Sample3 Sample4 Sample5 Sample6 Sample7
Species1 2 4 0 0 0 6 0
Species2 3 5 6 4 0 0 0
Species3 3 7 2 5 8 0 0
Species4 0 0 3 8 0 0 8
Species5 7 5 6 0 0 4 4
Species6 4 2 3 0 0 2 1
我想计算每行的中位数,然后将它们附加在新列中.我遇到了错误
I want to calculate the median of every row and append them in a new column. I got an error
参数"x"必须是向量或矩阵
Argument 'x' must be a vector or matrix
所以我尝试将df
转换为矩阵. str
函数显示该物种的每个值都是数字,所以我尝试了:
so I tried to convert my df
to a matrix. The str
function shows that every value for the species is numeric, so I tried:
library(matrixStats)
matrix(df, rownames.force = NA)
rowMedians(df)
但是我仍然遇到相同的错误.感谢您的帮助.
but I am still getting the same error. Any help is appreciated.
推荐答案
您不想包括该Abundance
列用于中值计算.假设df
是您当前的数据帧.
You don't want to include that Abundance
column for median calculation. Let df
be your current data frame.
library(matrixStats)
rowMedians(as.matrix(df[-1]))
除了上面的正确代码外,还有一些注释.
A few comments besides the correct code above.
- 您是否检查过
matrix(df)
是什么? - 即使正确返回了一个数字矩阵,它也不会覆盖
df
.所以rowMedians(df)
会给您同样的错误,好像什么也没发生; - 作为练习,比较
as.matrix(df[-1])
和as.matrix(df)
.
- Have you checked what
matrix(df)
is? - Even if it correctly returns you a numeric matrix, it does not overwrite
df
. SorowMedians(df)
gives you the same error as if nothing has happened; - As an exercise, compare
as.matrix(df[-1])
andas.matrix(df)
.
了解这些问题可防止您将来出错.
Understanding these issues prevents you from getting errors in future.
这篇关于使用matrixStats :: rowMedians查找每行的中位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!