使用 matrixStats::rowMedians 查找每一行的中位数
Find median of every row using matrixStats::rowMedians
我正在尝试使用 matrixStats
包中的 rowMedians
计算数据框 df
的行中位数。
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
我想计算每一行的中位数并将它们追加到新列中。我收到一个错误
Argument 'x' must be a vector or matrix
所以我尝试将我的 df
转换为矩阵。 str
函数显示物种的每个值都是数字,所以我尝试了:
library(matrixStats)
matrix(df, rownames.force = NA)
rowMedians(df)
但我仍然遇到同样的错误。感谢任何帮助。
我认为您需要删除第一列,因为它不是数字:
df$median_score <- apply(df[,-1], 1, median)
您不想在中位数计算中包括 Abundance
列。让 df
成为您当前的数据框。
library(matrixStats)
rowMedians(as.matrix(df[-1]))
除了上面的正确代码之外的一些评论。
- 你检查过
matrix(df)
是什么了吗?
- 即使它正确地 returns 你一个数字矩阵,它也不会覆盖
df
。所以 rowMedians(df)
给你同样的错误,就好像什么都没发生一样;
- 作为练习,比较
as.matrix(df[-1])
和 as.matrix(df)
。
了解这些问题可以防止您以后出错。
我正在尝试使用 matrixStats
包中的 rowMedians
计算数据框 df
的行中位数。
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
我想计算每一行的中位数并将它们追加到新列中。我收到一个错误
Argument 'x' must be a vector or matrix
所以我尝试将我的 df
转换为矩阵。 str
函数显示物种的每个值都是数字,所以我尝试了:
library(matrixStats)
matrix(df, rownames.force = NA)
rowMedians(df)
但我仍然遇到同样的错误。感谢任何帮助。
我认为您需要删除第一列,因为它不是数字:
df$median_score <- apply(df[,-1], 1, median)
您不想在中位数计算中包括 Abundance
列。让 df
成为您当前的数据框。
library(matrixStats)
rowMedians(as.matrix(df[-1]))
除了上面的正确代码之外的一些评论。
- 你检查过
matrix(df)
是什么了吗? - 即使它正确地 returns 你一个数字矩阵,它也不会覆盖
df
。所以rowMedians(df)
给你同样的错误,就好像什么都没发生一样; - 作为练习,比较
as.matrix(df[-1])
和as.matrix(df)
。
了解这些问题可以防止您以后出错。