-1
v1<-c(1,1,1,1,1,2,2,2,3,3,3,3,3,3,3)
v2<-c("Jan","Jan","Jan","Feb","Feb","Jan","Jan","Feb","Jan","Jan","Feb","Feb","Feb","Feb","Feb")
v3<-c("A1","E1","F1","B1","A1","E1","B1","C1","B1","D1","E1","A1","B1","C1","F1")
dt <- data.table(emp_id=v1,month=v2,work=v3)

enter image description here

I want to convert it into a dataframe/datatable such every work done by one emp_id is arranged sequentially as in the dt and is stored in a vector which is further stored in a column as shown below.

enter image description here

I have used

dt1 <- dt[, .(work = list(work)), emp_id]
temp<-as.vector(dt1$work[3])
length(temp)

But the result is showing 1. I want the sorting in such a way that it should show the result 3 as there are 3 elements in second row - E1,B1,C1 .

sid
  • 113
  • 1
  • 9

1 Answers1

0

We can place it in a list of vectors grouped by 'emp_id'

dt1 <- dt[, .(work = list(work)), emp_id]
dt1
#   emp_id               work
#1:      1     A1,E1,F1,B1,A1
#2:      2           E1,B1,C1
#3:      3 B1,D1,E1,A1,B1,C1,

dt1$work
[[1]]
#[1] "A1" "E1" "F1" "B1" "A1"

#[[2]]
#[1] "E1" "B1" "C1"

#[[3]]
#[1] "B1" "D1" "E1" "A1" "B1" "C1" "F1"

Or use split in to a named list of vectors

split(dt$work, dt$emp_id)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • But dt$work is not a vector? `vv<-as.vector(dt1$work[2])` and `length(vv)` then it is showing output as 1 instead of 3 i.e. (E1, B1, C1) – sid Jul 23 '17 at 09:21
  • @sid It is a `list` of `vector`s. You need to `is.vector(dt1$work[[2]])` – akrun Jul 23 '17 at 14:03