如何通过将r中的2列分组来确定唯一值的长度

问题描述 投票:0回答:1

我正在尝试根据2列有条件地提取唯一值的数量。我想做的是在同时考虑“变量”和“日期”时节省唯一观测值的长度,并将每个唯一观测值保存为列表,以便我可以循环运行每个观测值。以下是数据框和我一直在运行的代码的子集。 ncurves和id中应该有9个唯一的观察值。我在ncurves中得到2,ids保存为数据框,而不是要像我想要的那样通过循环运行的列表。

a <- structure(list(LightIntensity = c(0L, 112L, 0L, 112L, 0L, 112L, 0L, 112L, 0L, 112L, 0L, 
112L, 0L, 112L, 0L, 112L, 0L, 112L), variable = c(221L, 221L, 244L, 244L, 12L, 12L, 221L, 
221L, 244L, 244L, 12L, 12L, 221L, 221L, 12L, 12L, 244L, 244L), value = c(-1.21625718690742, 
0.192572605693232, -1.21625718690742, 0.226570039268424, -0.437571128774482, 
0.167029555798728, -0.344666861319387, -0.099033581577414, -0.341605586260893, 
0.158985219436985, -0.0728378731631007, 0.108468868197142, -0.227259158534414, 
-0.121668829961881, -0.504828403085384, 0.37919920958843, -0.674980508632225, 
0.215847519075345), Species = structure(c(1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L), .Label = c("Montipora capitata", "Porites compressa"), class = 
"factor"), Bleach = structure(c(1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 
2L, 2L, 2L), .Label = c("Bleach", "Non-bleach"), class = "factor"), Date = structure(c(1L, 
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("2019-09-16", 
"2019-10-02", "2019-10-16"), class = "factor")), row.names = c(1L, 
2L, 28L, 29L, 181L, 182L, 361L, 362L, 481L, 482L, 541L, 542L, 761L, 762L, 891L, 892L, 921L, 
922L), class = "data.frame")

n <- length(unique(a[c("variable", "Date")]))
ids <- unique(a[c("variable", "Date")])
r count unique
1个回答
0
投票

要提取data.frame中的唯一组合,可以执行以下操作:

a[!duplicated(a[c("variable", "Date")]),]

    LightIntensity variable       value            Species     Bleach       Date
1                0      221 -1.21625719 Montipora capitata     Bleach 2019-09-16
28               0      244 -1.21625719  Porites compressa Non-bleach 2019-09-16
181              0       12 -0.43757113 Montipora capitata Non-bleach 2019-09-16
361              0      221 -0.34466686 Montipora capitata     Bleach 2019-10-02
481              0      244 -0.34160559  Porites compressa Non-bleach 2019-10-02
541              0       12 -0.07283787 Montipora capitata Non-bleach 2019-10-02
761              0      221 -0.22725916 Montipora capitata     Bleach 2019-10-16
891              0       12 -0.50482840 Montipora capitata Non-bleach 2019-10-16
921              0      244 -0.67498051  Porites compressa Non-bleach 2019-10-16

要获取索引,您可以执行:

(ids <- which(!duplicated(a[c("variable", "Date")])))
[1]  1  3  5  7  9 11 13 15 17
© www.soinside.com 2019 - 2024. All rights reserved.