-1

Given an R data frame with the fallowing variables: ID, DATE and RATING.

'''
data<-data.frame(ID=c(1,1,1,2,3,4),DATE=c('2019-01-01','2019-02-01','2019-03-01','2019-02-01','2019-02-01','2019-02-01'),RATING=c('A','B','C','B','B','C'))
'''

How can I obtain the new.data object as a matrix or data.frame? The rownames of the new.data are related to variable ID within the data's object.

enter image description here

tudor.a
  • 49
  • 3

2 Answers2

0

Using data.table:

library(data.table)
setDT(data)
out <- data[, dcast(.SD, ID ~ DATE, value.var = "RATING")]
as.matrix(out, rownames = "ID")

  2019-01-01 2019-02-01 2019-03-01
1 "A"        "B"        "C"       
2 NA         "B"        NA        
3 NA         "B"        NA        
4 NA         "C"        NA    
s_baldur
  • 29,441
  • 4
  • 36
  • 69
0

Try pivot_wider :

data%>%
  pivot_wider(names_from = DATE, values_from = RATING)

 A tibble: 4 x 4
     ID `2019-01-01` `2019-02-01` `2019-03-01`
  <dbl> <chr>        <chr>        <chr>       
1     1 A            B            C           
2     2 NA           B            NA          
3     3 NA           B            NA          
4     4 NA           C            NA   
Dealec
  • 287
  • 1
  • 5