What is the meaning of ~ together?

x <- iris[,1:4]
names(x) <- c("x1","x2","x3","x4")
aggregate(x1+x2+x3+x4~x1,FUN=sum,data=x)

Here is the result, I wonder, 1. What is the meaning of ~the formula?
2. Why x1 = 4.3, x1 + x2 + x3 + x4equal to 8.5?

x1 x1 + x2 + x3 + x4
1 4.3 8.5 2 4.4 26.9
3 4.5 8.4

when i use

 transform(x,x1=sort(x1))

what i get:

     x1  x2  x3  x4  
1   4.3 3.5 1.4 0.2  
2   4.4 3.0 1.4 0.2  
3   4.4 3.2 1.3 0.2  
4   4.4 3.1 1.5 0.2  

(many output omitted)
When x1=4.3, x1 + x2 + x3 + x4not 3.5+1.4+0.2=5.1, 4.3+3.5+1.4+0.2=9.4huh?

+2
source share
3 answers

~in aggregate()shares on the left, is that "aggregates" and on the right side - that is used for "aggregation" elements.

x1 + x2 + x3 + x4 , , tuples, x1 .

, , 8.5, , :

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

x1 = 4.3 - 14- : 14 4.3 3.0 1.1 0.1.

, x1 FUN=sum .

x1 = 4.3, 8.5, 14.

+8

tilde . , , :

f = ~

[...]

f . R, , , . , f : " - ".

formula .

+5

, Iris , 4.3. :

(x[x[,1]==4.3,])

#     x1 x2  x3  x4
# 14 4.3  3 1.1 0.1

# and 4.3 + 3.0 + 1.1 + 0.1 = 8.5.

sum(x[x[,1]==4.3,])

# [1] 8.5


# There are four rows where x1 = 6.9.  Those rows are:

x[x[,1]==6.9,]

#      x1  x2  x3  x4
# 53  6.9 3.1 4.9 1.5
# 121 6.9 3.2 5.7 2.3
# 140 6.9 3.1 5.4 2.1
# 142 6.9 3.1 5.1 2.3

# and

# 6.9 + 3.1 + 4.9 + 1.5 +
# 6.9 + 3.2 + 5.7 + 2.3 +
# 6.9 + 3.1 + 5.4 + 2.1 +
# 6.9 + 3.1 + 5.1 + 2.3 = 69.4

sum(x[x[,1]==6.9,])

# [1] 69.4

, ,

transform(x,x1=sort(x1))

, , .

4,3 + 3,5 + 1,4 + 0,2 = 9,4

#      x1  x2  x3  x4
# 1   4.3 3.5 1.4 0.2
# 2   4.4 3.0 1.4 0.2
# 3   4.4 3.2 1.3 0.2
# 4   4.4 3.1 1.5 0.2
# 5   4.5 3.6 1.4 0.2

If you want to order a data set by increasing the values ​​of the first column without changing the data set, use:

x[order(x$x1),]

#      x1  x2  x3  x4
# 14  4.3 3.0 1.1 0.1
# 9   4.4 2.9 1.4 0.2
# 39  4.4 3.0 1.3 0.2
# 43  4.4 3.2 1.3 0.2
# 42  4.5 2.3 1.3 0.3
+1
source

Source: https://habr.com/ru/post/1546598/


All Articles