-2

I am using the symbol in the code as:

test[,income_level := ifelse(test$income_level=="-50000",0,1)]

Please help me understand the symbol ":="

moodymudskipper
  • 42,696
  • 10
  • 102
  • 146
Abhishek
  • 49
  • 1
  • 7
  • This mean you create a new column `income_level ` with value `ifelse(test$income_level=="-50000",0,1)`, or you can just think this way `test[,'income_level']=ifelse(test$income_level=="-50000",0,1)` – BENY Aug 12 '17 at 14:36
  • Take a look at this question to understand how the `:=` operator is parsed in base R and how it's redefined and used by some packages such as `data.table` and `ggvis`: https://stackoverflow.com/questions/26269423/r-why-is-allowed-as-an-infix-operator – Oriol Mirosa Aug 12 '17 at 14:39
  • 2
    It's not (any longer) a part of base R. It is used by a few packages, notably [data.table](https://github.com/Rdatatable/data.table/wiki) as in the usage you supply. – alistaire Aug 12 '17 at 15:01

1 Answers1

1

Most certainly the code you cite represents the modification of data.table object, which can only me made in R by loading an additional package, which is called data.table as well. More specifically, the code adds a new column to the test data.table.

A data.table is a data.frame but allows different syntax and can provide speed advantages.

Example:

# Load the data.table package
library(data.table) # First install.packages("data.table")

# Example data data
n <- 8
set.seed(1)
test <- data.table(id = 1:n, income = rnorm(n = n, mean = 1000, sd = 150))
test
   id    income
1:  1  906.0319
2:  2 1027.5465
3:  3  874.6557
4:  4 1239.2921
5:  5 1049.4262
6:  6  876.9297
7:  7 1073.1144
8:  8 1110.7487

# Create a new column
test[, income_high := ifelse(test$income > 1000, 1, 0)]
test
   id    income income_high
1:  1  906.0319           0
2:  2 1027.5465           1
3:  3  874.6557           0
4:  4 1239.2921           1
5:  5 1049.4262           1
6:  6  876.9297           0
7:  7 1073.1144           1
8:  8 1110.7487           1
sindri_baldur
  • 25,109
  • 3
  • 30
  • 57
  • 1
    I believe symbol := this signifies initiation and assignment of new object column in the present object. – Abhishek Aug 22 '17 at 14:26