I want to get both the minimum and a random sample of a variable by a group, in data.table.
data.table(ggplot2::movies)[, list(min=min(rating), random=sample(rating, 1)), by=list(year, Action)]
does not work:
Error in `[.data.table`(data.table(movies), , list(min(rating), sample(rating, :
Column 2 of result for group 88 is type 'integer' but expecting type 'double'. Column types must be consistent for each group.
If I force it to numerical, I get this astonishing result: categories whose random rating is under (?!!) the minimum of the same category.
data.table(ggplot2::movies)[, list(min=min(rating), random=as.numeric(sample(rating, 1))), by=list(year, Action)][random<min]
year Action min random
1: 1916 1 6.2 6
2: 1911 1 5.7 1
3: 1901 1 4.2 3
4: 1914 1 6.1 6
5: 1923 1 8.2 4
6: 1918 1 5.9 5
7: 1921 1 7.5 4
Using .SD
does not change anything:
data.table(ggplot2::movies)[, list(min=min(rating), random=as.numeric(sample(.SD$rating, 1))), by=list(year, Action)][random<min]
year Action min random
1: 1916 1 6.2 2
2: 1911 1 5.7 4
3: 1893 0 7.0 2
4: 1901 1 4.2 4
5: 1914 1 6.1 5
6: 1923 1 8.2 8
7: 1918 1 5.9 4
And the worse is that no error arise when the variable is integer:
data.table(ggplot2::movies)[, list(min=min(votes), random=sample(votes, 1)), by=list(year, Action)][random<min]
year Action min random
1: 1916 1 135 43
2: 1911 1 26 2
3: 1893 0 90 52
4: 1901 1 13 12
5: 1923 1 757 368
6: 1918 1 60 49
7: 1921 1 73 48
Apparently the sample
function does not want to work on the subset...
Help!