Home > Software engineering >  Creating new columns using data in one column and fill with data
Creating new columns using data in one column and fill with data

Time:03-26

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

CodePudding user response:

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))

CodePudding user response:

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
  •  Tags:  
  • r
  • Related