Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-arrange a table per group

Tags:

r

aggregate

I work with R and I have this data:

   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))

I would like to re-arrange it to see what is available or nor. The output would look like this:

    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))

I have tried with aggregate but I am still far from the result. Help would be

t <- aggregate(data$Col2, by=list(data$Col3), c)

Help is welcome!

like image 373
Floni Avatar asked Sep 27 '17 06:09

Floni


1 Answers

We can use dcast from data.table with length as fun.aggregate

library(data.table)
dcast(setDT(data), Col2~ Col3, length)[, 1:5, with = FALSE]
like image 144
akrun Avatar answered Oct 03 '22 02:10

akrun