What is the meaning of ~ in aggregate?

前端 未结 3 1952
滥情空心
滥情空心 2021-01-01 08:23
x <- iris[,1:4]
names(x) <- c(\"x1\",\"x2\",\"x3\",\"x4\")
aggregate(x1+x2+x3+x4~x1,FUN=sum,data=x)

Here is the output ,i wonder
1. What

3条回答
  •  旧时难觅i
    2021-01-01 08:51

    ~ in aggregate() separates, to the left side, what is being "aggregated", and to the right side, what is being used to "aggregate" the items.

    In your example, the result of x1 + x2 + x3 + x4 will be calculated for each row, and then summed up according to the group formed by tuples in which x1 appears with the same value.

    So, the reason why you have 8.5 is because, the data being summed is:

    x1 + x2 + x3 + x4 = sum(c(4.3, 3.0, 1.1, 0.1)) = 8.5
    

    The line with x1 = 4.3, in your example, is the 14th row: 14 4.3 3.0 1.1 0.1.

    The values are all summed up, and each resultant sum is aggregated by x1 value, and sent to FUN=sum for being summed.

    Since there's only one x1 = 4.3, the value will be simply 8.5, which is the result of the sum of entries from row 14th.

提交回复
热议问题