Home > Mobile >  Dealing with unique measurement at specific time-steps
Dealing with unique measurement at specific time-steps

Time:04-27

I would like to identify the number of unique measurement times. Based on the below example at t1 there is one unique measurement (e.g. 1). Two is not a unique measurement because it occurs twice at different positions. At t2 there is 0 unique measurement, at t3 there are again three unique measurements and at t4, t5, t6 and t7, there are zero. Therefore the sum of the total unique measurement is 4.

Data format:

enter image description here

Desired output

enter image description here

Sample data

df<-structure(list(t1 = c(1, 2, 2), t2 = c(1, 1, 1), t3 = c(1, 3, 
4), t4 = c(2, 2, 2), t5 = c(3, 3, 3), t6 = c(3, 3, 3), t7 = c(1, 
1, 1)), row.names = c(NA, -3L), spec = structure(list(cols = list(
    t1 = structure(list(), class = c("collector_double", "collector"
    )), t2 = structure(list(), class = c("collector_double", 
    "collector")), t3 = structure(list(), class = c("collector_double", 
    "collector")), t4 = structure(list(), class = c("collector_double", 
    "collector")), t5 = structure(list(), class = c("collector_double", 
    "collector")), t6 = structure(list(), class = c("collector_double", 
    "collector")), t7 = structure(list(), class = c("collector_double", 
    "collector"))), default = structure(list(), class = c("collector_guess", 
"collector")), delim = ","), class = "col_spec"),  class = c("spec_tbl_df", 
"tbl_df", "tbl", "data.frame"))

CodePudding user response:

Try this ...

library(tidyverse)

df <- structure(
  list(
    t1 = c(1, 2, 2),
    t2 = c(1, 1, 1),
    t3 = c(1, 3, 4),
    t4 = c(2, 2, 2),
    t5 = c(3, 3, 3),
    t6 = c(3, 3, 3),
    t7 = c(1, 1, 1)
  ),
  row.names = c(NA,-3L),
  spec = structure(
    list(
      cols = list(
        t1 = structure(list(), class = c("collector_double", "collector")),
        t2 = structure(list(), class = c("collector_double", "collector")),
        t3 = structure(list(), class = c("collector_double", "collector")),
        t4 = structure(list(), class = c("collector_double", "collector")),
        t5 = structure(list(), class = c("collector_double", "collector")),
        t6 = structure(list(), class = c("collector_double", "collector")),
        t7 = structure(list(), class = c("collector_double", "collector"))
      ),
    default = structure(list(), class = c("collector_guess", "collector")),
    delim = ","), class = "col_spec"),
  class = c("spec_tbl_df",
            "tbl_df", "tbl", "data.frame")
)

df |> 
  pivot_longer(everything()) |> 
  arrange(name, value) |> 
  count(name, value) |> 
  filter(n == 1) |> 
  group_by(name) |> 
  summarise(meas_num = str_c(value, collapse = ", "), count = sum(n))
#> # A tibble: 2 × 3
#>   name  meas_num count
#>   <chr> <chr>    <int>
#> 1 t1    1            1
#> 2 t3    1, 3, 4      3

Created on 2022-04-26 by the reprex package (v2.0.1)

  • Related