John_dydx
John_dydx

Reputation: 961

Re-arranging a grouped data in R

Using the Oats data as an example, I would like to obtain the following result below:

library(nlme)

dframe <- data.frame( Block = rep("I", 3), Variety = names(table(Oats[Oats$Block == "I",            ]$Variety)), Freq = as.vector(table(Oats[Oats$Block == "I", ]$Variety)))

        Block     Variety      Freq
    1     I      Golden Rain    4
    2     I      Marvellous     4
    3     I      Victory        4
    ...

I would like the above results for all other blocks II to VI in the Oats data. I was hoping there was a more efficient way of doing this in R without having to write separate codes for each of the Block ids. I've had a read through a few of the posts but still haven't found a solution yet. I've also tried using a few functions-aggregate, table, etc.

Thanks

Upvotes: 2

Views: 110

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

You can use table

> ( a <- as.data.frame(with(Oats, table(Block, Variety))) )
> a[order(a$Block, decreasing = TRUE), ]

Or plyr::count

> library(plyr)
> count(Oats, vars = c("Block", "Variety"))

And for my first ever data.table answer...
I think you can do the following, which would not require any re-ordering afterwards.

> library(data.table)
> setDT(Oats)[, .N, by = list(Block, Variety)]

data.table users, please correct me if that's wrong.

Upvotes: 4

Related Questions