-1

I have a column with elements: 1,2,3,4 how I can make 4 vectors i=1,2,3,4 which is 1 if that row is i, and -1 if it is not i.

example

mode
 1  
 3
 1
 2
 4
 1


   i1     i2     i3      i4     
   1     -1      -1      -1
  -1     -1       1      -1
   1     -1      -1      -1
  -1      1      -1      -1
  -1     -1      -1       1
   1     -1      -1      -1

I hope it is clear, for example first row is 1 so i1 is 1 and others are -1, second row is 3 so i3=1 and others -1 and so on

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
sherek_66
  • 501
  • 5
  • 14
  • Possible duplicate of https://stackoverflow.com/questions/5048638/automatically-expanding-an-r-factor-into-a-collection-of-1-0-indicator-variables/5048727 and the many linked questions in the sidebar which show alternative methods. – thelatemail Jul 11 '19 at 03:31
  • @Andreas if I knew how do that, I wouldn't ask! – sherek_66 Jul 11 '19 at 03:34
  • Possible duplicate of [Using ifelse Within apply](https://stackoverflow.com/questions/30769325/using-ifelse-within-apply) – morgan121 Jul 11 '19 at 03:35

2 Answers2

4

Instead of 4 vectors, this generates a matrix.

vec_mode <- c(1,3,1,2,4,1)

matr <- matrix(-1, nrow = length(vec_mode), ncol = max(vec_mode))
matr[cbind(seq_along(vec_mode), vec_mode)]<- 1

colnames(matr) <- paste0('i', seq_len(max(vec_mode)))

matr

     i1 i2 i3 i4
[1,]  1 -1 -1 -1
[2,] -1 -1  1 -1
[3,]  1 -1 -1 -1
[4,] -1  1 -1 -1
[5,] -1 -1 -1  1
[6,]  1 -1 -1 -1
Cole
  • 11,130
  • 1
  • 9
  • 24
1

One way using dplyr and tidyr is to create new columns with row_number and value (val) 1. spread it to wide format with fill = -1 to fill missing values.

library(dplyr)
library(tidyr)

df %>%
   mutate(row = row_number(), 
          val = 1,
          mode = paste0("i", mode)) %>%
   spread(mode, val, fill = -1) %>%
   select(-row)

#  i1 i2 i3 i4
#1  1 -1 -1 -1
#2 -1 -1  1 -1
#3  1 -1 -1 -1
#4 -1  1 -1 -1
#5 -1 -1 -1  1
#6  1 -1 -1 -1

data

df <- structure(list(mode = c(1L, 3L, 1L, 2L, 4L, 1L)), 
      class = "data.frame", row.names = c(NA, -6L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213