R

时间:2016-11-17 16:13:25

标签: r dataframe

我有示例数据框:

date            item1    item2    item3
17-11-2016      2A        hp       cnf
12-11-2016      1A        bp       wl
13-11-2016      3A        sp       dl
14-11-2016      1A        hp       cnf
16-11-2016      2A        bp       cnf
10-11-2016      1A        sp       wl
17-11-2016      2A        hp       wl

我想基于所有列date,item1和item2对数据进行分组,以便具有相同值的特定列将来到同一个组。

预期产出:

date            item1    item2    item3    grp
17-11-2016      2A        hp       cnf      1
17-11-2016      2A        hp       wl       1
12-11-2016      1A        bp       wl       2
13-11-2016      3A        sp       dl       3
14-11-2016      1A        hp       cnf      4
16-11-2016      2A        bp       cnf      5
10-11-2016      1A        sp       wl       6

2 个答案:

答案 0 :(得分:1)

你可以这样做:

DF <- data.frame(date = c("17-11-2016","12-11-2016","13-11-2016","14-11-2016",
                          "16-11-2016","10-11-2016","17-11-2016"),
                 item1 = c("2A","1A","3A","1A","2A","1A","2A"),
                 item2 = c("hp","bp","sp","hp","bp","sp","hp"),
                 item3 = c("cnf","wl","dl","cnf","cnf","wl","wl")
                 )
DF$grp <- as.numeric(factor(paste(DF$date,DF$item1,DF$item2)))
DF[order(DF$grp),]
        date item1 item2 item3 grp
6 10-11-2016    1A    sp    wl   1
2 12-11-2016    1A    bp    wl   2
3 13-11-2016    3A    sp    dl   3
4 14-11-2016    1A    hp   cnf   4
5 16-11-2016    2A    bp   cnf   5
7 17-11-2016    2A    hp    wl   6
1 17-11-2016    2A    hp   cnf   6

答案 1 :(得分:0)

我们可以X509KeyManager前三列,转换为paste,将factor指定为'v1'中的levels元素并将其强制转换为{{1} }}

unique

或使用integer

v1 <- do.call(paste, df1[1:3])
df1$grp <- as.integer(factor(v1, levels = unique(v1)))
df1$grp
#[1] 1 1 2 3 4 5 6