In follow-up to this post. How do we use the dplyr or data.table package to match the factor levels appropriately with shared row names?
library(data.table)
(DT = data.table(a = LETTERS[c(1, 1:3, 8)], b = c(2, 4:7),
c = as.factor(c("bob", "mary", "bob", "george", "alice")), key="a"))
# a b c
# 1: A 2 bob
# 2: A 4 mary
# 3: B 5 bob
# 4: C 6 george
# 5: H 7 alice
...and using @frank 's great answer:
uc <- sort(unique(as.character(DT$c)))
( DT[,(uc):=lapply(uc,function(x)ifelse(c==x,b,NA))][,c('b','c'):=NULL] )
Returns:
# a alice bob george mary
# 1 A NA 2 NA NA
# 2 A NA NA NA 4
# 3 B NA 5 NA NA
# 4 C NA NA 6 NA
# 5 H 7 NA NA NA
And the final question here is, how do we get the below output, where unique row names share level values returning NAs where empty elements remain?
alice bob george mary
# 1 A NA 2 NA 4
# 2 B NA 5 NA NA
# 3 C NA NA 6 NA
# 4 H 7 NA NA NA