'Creating new columns using data in one column and fill with data

If I have a data frame like this:

dt <- data.frame(cols = letters[1:6])
dt
#>   cols
#> 1    a
#> 2    b
#> 3    c
#> 4    d
#> 5    e
#> 6    f

How to create new columns using data in the cols column (with 1s on the diagonal):

  a b c d e f
a 1 0 0 0 0 0
b 0 1 0 0 0 0
c 0 0 1 0 0 0 
d 0 0 0 1 0 0
e 0 0 0 0 1 0
f 0 0 0 0 0 1
r


Solution 1:[1]

In base R, we can use table

out <-table(dt$col, dt$col)

-output

out
    a b c d e f
  a 1 0 0 0 0 0
  b 0 1 0 0 0 0
  c 0 0 1 0 0 0
  d 0 0 0 1 0 0
  e 0 0 0 0 1 0
  f 0 0 0 0 0 1

Or use diag

 `dimnames<-`(diag(nrow(dt)), list(dt$col, dt$col))

Solution 2:[2]

Another possible solution:

m <- matrix(0, 6, 6, dimnames = list(dt$cols, dt$cols))
diag(m) <- 1

m

#>   a b c d e f
#> a 1 0 0 0 0 0
#> b 0 1 0 0 0 0
#> c 0 0 1 0 0 0
#> d 0 0 0 1 0 0
#> e 0 0 0 0 1 0
#> f 0 0 0 0 0 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 akrun
Solution 2 PaulS