1

I would like to understand the meaning of ~. in R. This is an example from kknn function:

library(kknn)

data(iris)
m <- dim(iris)[1]
val <- sample(1:m, size = round(m/3), replace = FALSE, prob = rep(1/m, m)) 
iris.learn <- iris[-val,]
iris.valid <- iris[val,]
iris.kknn <- kknn(Species~., iris.learn, iris.valid, distance = 1, kernel = "triangular")
summary(iris.kknn)
fit <- fitted(iris.kknn)
table(iris.valid$Species, fit)

It is included on the kknn function above, right beside the Species.

Thank you!

Lëmön
  • 322
  • 2
  • 14

2 Answers2

2

Here ~ is a separator, and . stands for all other attributes. Here you mean that, you have to predict Species~[separator] based on all other attributes[.]

Niranjan Agnihotri
  • 916
  • 2
  • 11
  • 19
2

As you can see here, you are creating a formula object. The documentation of formula states:

There are two special interpretations of . in a formula. The usual one is in the context of a data argument of model fitting functions and means ‘all columns not otherwise in the formula’

So in your case, you are creating a model that uses all other variables than 'Species' as predictors to predict Species.

Florian
  • 24,425
  • 4
  • 49
  • 80