3

I am trying to count how many different responses a person gives during a trial of an experiment, but there is a catch.

There are supposed to be 6 possible responses (1,2,3,4,5,6) BUT sometimes 0 is recorded as a response (it's a glitch / flaw in design).

I need to count the number of different responses they give, BUT ONLY counting unique values within the range 1-6. This helps us calculate their accuracy.

Is there a way to exclude the value 0 from contributing to a unique value counter? Any other work-arounds?

Currently I am trying this method below, but it includes 0, NA, and I think any other entry in a cell in the Unique Value Counter Column (I have named "Span6"), which makes me sad.

# My Span6 calculator:
ASixImageTrials <- data.frame(eSOPT_831$T8.RESP, eSOPT_831$T9.RESP, eSOPT_831$T10.RESP, eSOPT_831$T11.RESP, eSOPT_831$T12.RESP, eSOPT_831$T13.RESP)
ASixImageTrials$Span6 = apply(ASixImageTrials, 1, function(x) length(unique(x)))
Joshua
  • 40,822
  • 8
  • 72
  • 132
Jordan Garner
  • 147
  • 1
  • 2
  • 9

2 Answers2

2

could you edit your question and clarify why this doesn't solve your problem?

# here is a numeric vector with a bunch of numbers
mtcars$carb

# here is how to limit that vector to only 1-6
mtcars$carb[ mtcars$carb %in% 1:6 ]

# here is how to tabulate that result
table( mtcars$carb[ mtcars$carb %in% 1:6 ] )
Anthony Damico
  • 5,779
  • 7
  • 46
  • 77
2

Use na.omit inside unique and sum logic vector as below

df$res = apply(df, 1, function(x) sum(unique(na.omit(x)) > 0))
df

Output:

   X1 X2 X3 X4 X5 res
1   2  1  1  2  1   2
2   3  0  1  1  2   3
3   3 NA  1  1  3   2
4   3  3  3  4 NA   2
5   1  1  0 NA  3   2
6   3 NA NA  1  1   2
7   2  0  2  3  0   2
8   0  2  2  2  1   2
9   3  2  3  0 NA   2
10  0  2  3  2  2   2
11  2  2  1  2  1   2
12  0  2  2  2 NA   1
13  0  1  4  3  2   4
14  2  2  1  1 NA   2
15  3 NA  2  2 NA   2
16  2  2 NA  3 NA   2
17  2  3  2  2  2   2
18  2 NA  3  2  2   2
19 NA  4  5  1  3   4
20  3  1  2  1 NA   3

Data:

set.seed(752)
mat <- matrix(rbinom(100, 10, .2), nrow = 20)
mat[sample(1:100, 15)] = NA
data.frame(mat) -> df
df$res = apply(df, 1, function(x) sum(unique(na.omit(x)) > 0))
Pafnucy
  • 608
  • 1
  • 13
  • 17