2017-07-23 104 views
-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排序數據和合並

我想將其轉換成一個數據幀/數據表,例如每work由一個emp_id完成佈置依次dt並且被存儲在一個載體,其進一步存儲在如下所示的列中。

enter image description here

我已經使用

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

但結果是表示1。我想要這樣排序,它應該顯示結果3,因爲在第二行中有3個元素 - E1,B1,C1

回答

0

我們可以將它放在vectorlist A S由 '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" 

或使用中split一個名爲listvector小號

split(dt$work, dt$emp_id) 
+0

但是DT $工作分組不是矢量嗎? 'vv <-as.vector(dt1 $ work [2])'和 'length(vv)'然後顯示輸出爲1而不是3即(E1,B1,C1) – sid

+0

@sid這是一個'list矢量''的''。你需要'is.vector(dt1 $ work [[2]])'' – akrun