按类似观察结果分组-行

时间:2019-12-02 08:25:33

标签: r

      Col1  Col2 Col3 Col4
row1   a    b     b1    c
row2   a    b     b2    c
row3   a    b     b3    c
row4   a    b     b4    c

上面提到的是场景,

我想得到一个输出,


     col1 col2 col3  col4   col5  col6  col7
row1  a    b    b1    b2     b3    b4    c

只有一列具有相同的值时,如何减少行数。

1 个答案:

答案 0 :(得分:0)

也许您可以尝试以下代码:

v<- t(as.matrix(sort(unique(unlist(df)))))
setNames(data.frame(v),paste0("col",seq_along(v)))

数据

df <- structure(list(Col1 = structure(c(1L, 1L, 1L, 1L), .Label = "a", class = "factor"), 
    Col2 = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "b"), 
    Col3 = structure(1:4, .Label = c("b1", "b2", "b3", "b4"), class = "factor"), 
    Col4 = structure(c(1L, 1L, 1L, 1L), class = "factor", .Label = "c")), class = "data.frame", row.names = c("row1", 
"row2", "row3", "row4"))