3

I have an vector of integers y <- c(1, 2, 3, 3) and now I want to convert it into an list like this (one hot encoded):

1 0 0 
0 1 0
0 0 1
0 0 1

I tried to find a solution with to_categorical but I had problems with data types... Do anyone know a smart and smooth solution for this task?

This is my try:

 for (i in 1:length(y)) {
  one_character <- list(as.vector(to_categorical(y[[i]], num_classes = 3)))
  list_test <- rbind(list_test, one_character)
  }

but I get the following error:

Error in py_call_impl(callable, dots$args, dots$keywords) : 
  IndexError: index 3 is out of bounds for axis 1 with size 3
Henryk Borzymowski
  • 988
  • 1
  • 10
  • 22

4 Answers4

5

Here is one way in base R. Create a matrix of 0s and assign 1 based on the sequence of rows and y value as column index

m1 <- matrix(0, length(y), max(y))
m1[cbind(seq_along(y), y)] <- 1
m1
#      [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    0    1    0
#[3,]    0    0    1
#[4,]    0    0    1

In base R, we can also do

table(seq_along(y), y)
#  y
#    1 2 3
#  1 1 0 0
#  2 0 1 0
#  3 0 0 1
#  4 0 0 1

Or another option is model.frame from base R

model.matrix(~factor(y) - 1)
akrun
  • 874,273
  • 37
  • 540
  • 662
3

I prefer @akrun's answer for simplicity, but some alternatives:

Data:

dat <- data.frame(y=c(1,2,3,3))
dat$id <- seq_len(nrow(dat))
dat$one <- 1L

With an "id" field added to keep the rows separate/unique. Since I'm reshaping the data, I need a value to retain, so the temp variable "one".

Base R

dat_base <- reshape(dat, idvar="id", v.names="one", timevar="y", direction="wide")
dat_base[2:4] <- lapply(dat_base[2:4], function(a) replace(a, is.na(a), 0))
dat_base
#   id one.1 one.2 one.3
# 1  1     1     0     0
# 2  2     0     1     0
# 3  3     0     0     1
# 4  4     0     0     1

dplyr

library(dplyr)
library(tidyr)
dat %>%
  spread(y, one) %>%
  mutate_all(~if_else(is.na(.), 0L, .))
#   id 1 2 3
# 1  1 1 0 0
# 2  2 0 1 0
# 3  3 0 0 1
# 4  4 0 0 1

data.table

library(data.table)
datdt <- as.data.table(dat)
dcast(datdt, id ~ y, value.var = "one", fill = 0)
#    id 1 2 3
# 1:  1 1 0 0
# 2:  2 0 1 0
# 3:  3 0 0 1
# 4:  4 0 0 1
r2evans
  • 141,215
  • 6
  • 77
  • 149
2

One-liner with mltools and data.table:

one_hot(as.data.table(as.factor(y)))
   V1_1 V1_2 V1_3
1:    1    0    0
2:    0    1    0
3:    0    0    1
4:    0    0    1
Roman
  • 4,744
  • 2
  • 16
  • 58
1

Yet another option provides the splitstackshape package.

y <- c(1, 2, 3, 3)
splitstackshape:::numMat(y, fill = 0L)
#     1 2 3
#[1,] 1 0 0
#[2,] 0 1 0
#[3,] 0 0 1
#[4,] 0 0 1
markus
  • 25,843
  • 5
  • 39
  • 58