排序数据和合并

时间:2017-07-23 08:45:20

标签: r dataset mergesort data-analysis

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_iddt排列顺序并存储在一个向量,它进一步存储在一列中,如下所示。

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

1 个答案:

答案 0 :(得分:0)

我们可以将其放置在list vector的{​​{1}}分组中,其中包含&#39; emp_id&#39;

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用于list的{​​{1}}

vector