我使用R,并且有以下数据:

   data <- structure(list(Col1 = 1:9, Col2 = structure(c(2L, 2L, 2L, 1L,
3L, 3L, 3L, 3L, 3L), .Label = c("Administrative ", "National",
"Regional"), class = "factor"), Col3 = structure(c(NA, 3L, 4L,
NA, 2L, 3L, 1L, 4L, 3L), .Label = c("bike", "boat", "car", "truck"
), class = "factor"), Col4 = c(56L, 65L, 58L, 62L, 24L, 25L,
120L, 89L, 468L), X = c(NA, NA, NA, NA, NA, NA, NA, NA, NA),
    X.1 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c("Col1",
"Col2", "Col3", "Col4", "X", "X.1"), class = "data.frame", row.names = c(NA,
-9L))

我想重新安排它,看看有什么可用或没有。输出如下所示:
    result <- structure(list(Col1 = c(1L, 4L, 5L), Col2 = structure(c(2L, 1L,
3L), .Label = c("Administrative ", "National", "Regional"), class = "factor"),
    car = c(1L, 0L, 1L), truck = c(1L, 0L, 1L), boat = c(0L,
    0L, 1L), bike = c(0L, 0L, 1L)), .Names = c("Col1", "Col2",
"car", "truck", "boat", "bike"), class = "data.frame", row.names = c(NA,
-3L))

我已经尝试使用聚合,但距离结果还差得远。帮助会是
t <- aggregate(data$Col2, by=list(data$Col3), c)

欢迎提供帮助!

最佳答案

我们可以使用dcast中的data.table,并将length作为fun.aggregate

library(data.table)
dcast(setDT(data), Col2~ Col3, length)[, 1:5, with = FALSE]

关于每组重新安排一张 table ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46441327/

10-09 16:57