如何计算物种矩阵中一行中唯一的数量?

Cla*_*ire 8 r dataframe vegan

我试图确定哪些行具有唯一性(仅在该行中观察到的物种,而不是在物种矩阵的任何其他行中观察到的物种)。我设置了数据矩阵,其中列作为单独的物种,行作为单独的采样单位(在我们的例子中为横断面)。

例如,物种 1 仅在第 8 行中找到,而在数据集中没有其他位置,那么我想知道第 8 行包含 1 个唯一物种。如果物种 4 也只在第 8 行中发现,那么唯一物种的数量将为 2 等。注意:我在数据集中发现的一些唯一物种的丰度大于 1,这意味着它们在横断面上被发现的数量更多不止一次,但它们仍然只在该横断面中被发现(仍然被认为是唯一的)。

以下是一些示例数据,其中第 3 行有两个唯一值,第 5 行有 1 个唯一值:

 example_data <- data.frame(Species1 = c(1, 2, 3, 4, 5),
                             Species2 = c(6, 7, 8, 9, 10),
                             Species3 = c(0, 0, 13, 0, 0),
                             Species4 = c(0, 0, 0, 0, 20),
                             Species5 = c(0, 0, 23, 0, 0))
Run Code Online (Sandbox Code Playgroud)

尝试使用 ChatGPT 但一无所获,我能够通过 VIA excel 找出该数据集确实具有唯一性。我还想出了如何让 R 告诉我哪些物种只被发现一次,但我更感兴趣的是哪些行(横断面)具有唯一性以及有多少,而不是哪些物种是唯一的。

另外,有没有一种方法可以列出所有行和唯一值的数量?对于示例数据,它将是 0,0,2,0,1。我感兴趣的是哪些行也没有唯一性(0 个唯一性)。

jps*_*ith 6

因为您感兴趣的是哪些行具有唯一性以及有多少行,而不是哪些物种是唯一的:

您可以通过首先查找哪些物种是唯一的来找到具有唯一值的行和列索引,然后使用which(..., ind.arr = TRUE):

uniques <- vapply(example_data, \(x) sum(x !=0) == 1, logical(1L))

# Species1 Species2 Species3 Species4 Species5 
#    FALSE    FALSE     TRUE     TRUE     TRUE 

rowcol_uniques <- which(example_data[uniques] != 0, arr.ind = TRUE)
rownames(rowcol_uniques) <- names(uniques[uniques])

#            row col
# Species3   3   1
# Species4   5   2
# Species5   3   3
Run Code Online (Sandbox Code Playgroud)

您可以通过以下方式找到有多少table:

table(rowcol_uniques[,1])

# 3 5 
# 2 1 
Run Code Online (Sandbox Code Playgroud)

在您的编辑中,您提到您感兴趣的行也没有唯一性 - 为此您可以merge,这将创建第二列Freq,用于标识所有行每行的唯一性数量:

anyuniques <- merge(data.frame(row = seq_len(nrow(example_data))), 
                    as.data.frame(table(row = rowcol_uniques[,1])), 
                    all.x = TRUE)
anyuniques[is.na(anyuniques)] <- 0

#   row Freq
# 1   1    0
# 2   2    0
# 3   3    2
# 4   4    0
# 5   5    1
Run Code Online (Sandbox Code Playgroud)


Maë*_*aël 6

您可以像这样使用colSums+ :rowSums

cbind(example_data,
      uniques = rowSums(example_data[colSums(example_data > 0) == 1] > 0))

#   Species1 Species2 Species3 Species4 Species5 uniques
# 1        1        6        0        0        0       0
# 2        2        7        0        0        0       0
# 3        3        8       13        0       23       2
# 4        4        9        0        0        0       0
# 5        5       10        0       20        0       1
Run Code Online (Sandbox Code Playgroud)

要检查唯一值的位置,您可以执行以下操作:

which(example_data[colSums(example_data > 0) == 1] > 0, arr.ind = TRUE)

#      row col
# [1,]   3   1
# [2,]   5   2
# [3,]   3   3
Run Code Online (Sandbox Code Playgroud)