how to transform this matrix in R ? (one-hot,chr)

Viewed 46

now I have like this data.

matrix_in_matrix<-data.frame()
matrix_in_matrix[1,1]<-"red-green-blue-yellow"
matrix_in_matrix[2,1]<-"red-green-blue"
matrix_in_matrix[3,1]<-"red-green-yellow"
matrix_in_matrix[4,1]<-"green-blue-yellow"
matrix_in_matrix
#                      V1
# 1 red-green-blue-yellow
# 2        red-green-blue
# 3      red-green-yellow
# 4     green-blue-yellow

I want to transform like follows.

onehot <- data.frame(red=c(1,1,1,0),
           green=c(1,1,1,1),
           blue=c(1,1,0,1),
           yellow=c(1,0,1,1))
onehot
#   red green blue yellow
# 1   1     1    1      1
# 2   1     1    1      0
# 3   1     1    0      1
# 4   0     1    1      1

I think I should use split at - but I used split function, dataframe was changed list in list...

how can I fix it?

2 Answers

Using cSplit_e from splitstackshape

library(splitstackshape)
out <- cSplit_e(matrix_in_matrix, 'V1', sep="-", fill = '0', 
        type = 'character', drop = TRUE)
names(out) <- sub('V1_', '', names(out))

-output

out
#  blue green red yellow
#1    1     1   1      1
#2    1     1   1      0
#3    0     1   1      1
#4    1     1   0      1

Or an option with mtabulate

library(qdapTools)
mtabulate(strsplit(matrix_in_matrix$V1, "-"))
#  blue green red yellow
#1    1     1   1      1
#2    1     1   1      0
#3    0     1   1      1
#4    1     1   0      1

Here is a base R option

as.data.frame(
  do.call(
    rbind,
    lapply(
      u <- strsplit(matrix_in_matrix$V1, "-"),
      function(x) table(factor(x, levels = unique(unlist(u))))
    )
  )
)

which gives

  red green blue yellow
1   1     1    1      1
2   1     1    1      0
3   1     1    0      1
4   0     1    1      1
Related