我有以下样本数据:
set.seed(25)
xx <- data.table(
year = 2015,
values = iris$Sepal.Length,
score = sample(1:8, nrow(iris), replace = TRUE))实际数据包含许多年和行。我想使用values R中的cut()函数对base列进行分组,但是结果与LibreOffice Calc (甚至在MS )支点生成的结果不同。这就是我到目前为止所做的:
brks <- seq(0, ceiling(max(xx$values)), 0.5)
xx[, bins := cut(values, brks, ordered_result = TRUE)]
xx_binned <- dcast(xx, bins ~ year, length, value.var = "values")
xx_binned <- melt(xx_binned, id.vars = "bins", value.name = "value")我从0开始,这样如果我使用不同的数据,它将是一致的。在电子表格中,我也从0开始作为起始编号。
上述守则的结果是:
bins variable value
1 (4,4.5] 2015 5
2 (4.5,5] 2015 27
3 (5,5.5] 2015 27
4 (5.5,6] 2015 30
5 (6,6.5] 2015 31
6 (6.5,7] 2015 18
7 (7,7.5] 2015 6
8 (7.5,8] 2015 6这是LibreOffice Calc的结果:
values 2015
4-4.5 15
4.5-5 106
5-5.5 100
5.5-6 142
6-6.5 148
6.5-7 95
7-7.5 25
7.5-8 27我怎么才能做到同样的呢?我正在编写一个函数,将电子表格工具转换为R函数,我希望它与电子表格的输出相同。
谢谢。
发布于 2020-02-12 08:31:35
您必须对score进行总结,而不是要得到相同值的案例数。
aggregate(xx$score, list(cut(xx$values, brks, right=FALSE, ordered_result = TRUE)), sum)
# Group.1 x
#1 [4,4.5) 15
#2 [4.5,5) 106
#3 [5,5.5) 100
#4 [5.5,6) 142
#5 [6,6.5) 148
#6 [6.5,7) 95
#7 [7,7.5) 25
#8 [7.5,8) 27或更新代码:
library(data.table)
xx <- data.table(xx)
xx[, bins := cut(values, brks, right=FALSE, ordered_result = TRUE)]
dcast(xx, bins ~ year, sum, value.var = "score")数据:
set.seed(25)
xx <- data.frame(
year = 2015,
values = iris$Sepal.Length,
score = sample(1:8, nrow(iris), replace = TRUE))
brks <- seq(0, ceiling(max(xx$values)), 0.5)https://stackoverflow.com/questions/60183875
复制相似问题