Write R code to create a variable called 'city' with the value 'London', a variable called 'population' with a numeric value of 900, and then print the sentence: "The city of <city> has <population> people."
Variables are used to store data in R. You can assign values using the <-
operator or =
. R supports several basic data types:
42
or 3.14
"Hello"
TRUE
or FALSE
L
suffix, e.g., 10L
You can check the type of a variable using the class()
function.
num <- 42
char <- "Hello"
logi <- TRUE
int <- 10L
fac <- factor(c("Red", "Green", "Blue"))
class(num)
class(char)
class(logi)
class(int)
class(fac)
Output:
[1] "numeric"
[1] "character"
[1] "logical"
[1] "integer"
[1] "factor"
You can also create multiple variables and use them in calculations or string operations:
first_name <- "Joe"
last_name <- "Slug"
full_name <- paste(first_name, last_name)
age <- 25
next_year_age <- age + 1
print(full_name)
print(next_year_age)