0

I have three columns named i1,i2 and i3. Each of these columns is a vector of equal length. Each of them contain 1 and -1. I want to have an output column where the value should be

  • 1 if all the entires in i1,i2 and i3 is 1
  • -1 if all the entries in i1,i2 and i3 is -1
  • 0 for any other values Please suggest the way forward.

three columns of a data frame

3 Answers3

3

Just try (x is your matrix):

(rowSums(x==1)==ncol(x)) - (rowSums(x==-1)==ncol(x))
nicola
  • 24,005
  • 3
  • 35
  • 56
1

You can try the following

set.seed(1)
(x <- matrix(sample(c(-1,1), 60, TRUE), ncol = 3))

#       [,1] [,2] [,3]
#  [1,]   -1    1    1
#  [2,]   -1   -1    1
#  [3,]    1    1    1
#  [4,]    1   -1    1
#  [5,]   -1   -1    1
#  [6,]    1   -1    1
#  [7,]    1   -1   -1
#  [8,]    1   -1   -1
#  [9,]    1    1    1
# [10,]   -1   -1    1
# [11,]   -1   -1   -1
# [12,]   -1    1    1
# [13,]    1   -1   -1
# [14,]   -1   -1   -1
# [15,]    1    1   -1
# [16,]   -1    1   -1
# [17,]    1    1   -1
# [18,]    1   -1    1
# [19,]   -1    1    1
# [20,]    1   -1   -1

When the row sums are 3 or -3, multiply by the sign

rs <- rowSums(x)
cbind(x, ind = (abs(rs) == 3) * sign(rs))

#                ind
#  [1,] -1  1  1   0
#  [2,] -1 -1  1   0
#  [3,]  1  1  1   1
#  [4,]  1 -1  1   0
#  [5,] -1 -1  1   0
#  [6,]  1 -1  1   0
#  [7,]  1 -1 -1   0
#  [8,]  1 -1 -1   0
#  [9,]  1  1  1   1
# [10,] -1 -1  1   0
# [11,] -1 -1 -1  -1
# [12,] -1  1  1   0
# [13,]  1 -1 -1   0
# [14,] -1 -1 -1  -1
# [15,]  1  1 -1   0
# [16,] -1  1 -1   0
# [17,]  1  1 -1   0
# [18,]  1 -1  1   0
# [19,] -1  1  1   0
# [20,]  1 -1 -1   0
rawr
  • 20,481
  • 4
  • 44
  • 78
0

You can do

f <- function(x) ifelse(all(x==1), 1, ifelse(all(x==-1), -1, 0))
apply(df, 1, f) # or:
df$result <- apply(df, 1, f)
jogo
  • 12,469
  • 11
  • 37
  • 42