我希望在data.table中,按组获取一个变量的最小值和随机抽样。
data.table(ggplot2::movies)[, list(min=min(rating), random=sample(rating, 1)), by=list(year, Action)]
无法工作:
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.
如果我将其强制转换为数字,我会得到一个惊人的结果:随机评分低于(?!!)相同类别的最小值的类别。
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
使用.SD
不会改变任何东西:
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
更糟糕的是,当变量是整数时没有出现错误:
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
显然,
sample
函数不想在子集上工作...帮帮我!
data.table(iris)[, .(min = min(Sepal.Length), rand = sample(Sepal.Length,1)), by=.(Species)]
。我很好奇你是否发现了一个错误,但如果没有示例,我们无法确认它。 - Frank%>%
并在movies
前面添加ggplot2::
。我会编辑我的问题。 - Arthur