पाठ 3 / 25
Assignment, Types and Basic Operations
Assign values and use R's atomic types, special values and type checks.
The building blocks
Assign values with <- (the conventional R assignment operator; = also works at the top level, and RStudio inserts <- with Alt and minus). Names are case-sensitive and conventionally use snake_case. R's basic atomic types are double (numbers, the default: 3 is a double), integer (written with L: 3L), character (strings in double or single quotes), logical (TRUE/FALSE), complex and raw. Even a single value is a vector of length one. Check types with typeof(), class() and functions such as is.numeric(), and convert with as.numeric(), as.character() and as.integer() (failed conversions produce NA with a warning). Special values: NA (missing value, which propagates: NA + 1 is NA), NULL (absence of a value), NaN (not a number) and Inf. Arithmetic includes %/% (integer division) and %% (remainder). Use paste()/paste0() or sprintf() to build strings, and print(), cat() or simply typing a name in the console to see values.
Types, conversions and missing values
NA propagates through calculations unless you remove it explicitly.
price <- 499.5 # double
qty <- 3L # integer
city <- "Pune" # character
in_stock <- TRUE # logical
typeof(qty) # "integer"
class(price) # "numeric"
total <- price * qty
paste0("Total for ", qty, " items in ", city, ": ", total)
sprintf("%.2f INR", total)
as.numeric("42") # 42
as.numeric("forty-two") # NA with a warning
marks <- c(72, NA, 90)
mean(marks) # NA: missing values propagate
mean(marks, na.rm = TRUE) # 81: ignore missing values
17 %/% 5 # 3 (integer division)
17 %% 5 # 2 (remainder)NA is contagious
Any calculation involving NA returns NA, and x == NA is always NA, never TRUE. Use is.na(x) to test for missing values and na.rm = TRUE in summary functions.
त्वरित जाँच: What does mean(c(72, NA, 90)) return?
- 81
- 0
- NA
- An error
Answer
NA — Missing values propagate unless na.rm = TRUE is used.