Reputation: 646
Working with the iris data set I want to generate 4 ranges and dispose them in columns. Besides, I would like to have 4 additional columns with the quantities contained in each range.
I'm giving you the code for what I've done so far to get the information.
library(data.table)
setDT(iris)[ , bins := cut(Sepal.Length,4), by = list(Species)]
setDT(iris)[ , bins_n := table(bins), by = list(Species)]
table(iris[iris$Species=='setosa',]$bins)
(4.9,5.65] (5.65,6.4] (6.4,7.15] (7.15,7.9]
9 19 17 5
iris2<-data.frame(species="setosa",D1="(4.9,5.65]",D2="(5.65,6.4]",D3="(6.4,7.15]",D4="(7.15,7.9]",C1=9,C2=19,C3=17,C4=5)
So, the final output would be
species D1 D2 D3 D4 C1 C2 C3 C4
1 setosa (4.9,5.65] (5.65,6.4] (6.4,7.15] (7.15,7.9] 9 19 17 5
Even better if I can add the other Species with its ranges below.
Thanks!
Upvotes: 1
Views: 35
Reputation: 886938
We could do a stack
and reshape it to 'wide' from the 'tbl' output
library(data.table)
dcast(setDT(stack(as.list(tbl)))[, species := "setosa"],
species ~ rowid(species), value.var = c("ind","values"))
If we want it for all the 'species'
dcast(iris[, .(C =.N), .((D = bins),Species)],
Species ~ rowid(Species), value.var = c("D", "C"), sep="")
# Species D1 D2 D3 D4 C1 C2 C3 C4
#1: setosa (6.4,7.15] (5.65,6.4] (4.9,5.65] (7.15,7.9] 17 19 9 5
#2: versicolor (7.15,7.9] (6.4,7.15] (5.65,6.4] (4.9,5.65] 9 15 20 6
#3: virginica (5.65,6.4] (6.4,7.15] (7.15,7.9] (4.9,5.65] 22 15 11 2
tbl <- table(iris[iris$Species=='setosa',]$bins)
Upvotes: 1