Web Application Development with R Using Shiny(Third Edition)
上QQ阅读APP看书,第一时间看更新

Variable types

R is a dynamically typed language, and you are not required to declare the type of your variables when using it. Of course, it is worth knowing about the different types of variable that you might read or write using R. The different types of variable can be stored in a variety of structures, such as vectors, matrices, and dataframes, although some restrictions apply as mentioned previously (for example, matrices must contain only one variable type). The following bullet list contains the specifics of using these variable types:

  • Declaring a variable with at least one string in it will produce a vector of strings (in R, the character data type), as shown in the following code:
    > c("First", "Third", 4, "Second")
    [1] "First"  "Third"  "4"  "Second"
  • You will notice that the numeral 4 is converted to a string, "4". This is as a result of coercion, in which elements of a data structure are converted to other data types in order to fit within the types that are allowed within the data structure. Coercion occurs automatically, as in this case, or with an explicit call to the as() function—for example, as.numeric(), or as.Date().
  • Declaring a variable that contains only numbers will produce a numeric vector, as shown in the following code:
    > c(15, 10, 20, 11, 0.4, -4)
    [1] 15.0 10.0 20.0 11.0  0.4 -4.0  
  • R, of course, also includes a logical data type, as shown in the following code:
    > c(TRUE, FALSE, TRUE, TRUE, FALSE)
    [1]  TRUE FALSE  TRUE  TRUE FALSE
  • A data type exists for dates, which are often a source of problems for beginners, as shown in the following code:
    > as.Date(c("2013/10/24", "2012/12/05", "2011/09/02"))
    [1] "2013-10-24" "2012-12-05" "2011-09-02"
  • The use of the factor data type tells R all of the possible values of a categorical variable, such as gender or species, as shown in the following code:
    > factor(c("Male", "Female", "Female", "Male", "Male"),
      levels = c("Female", "Male"))
    [1] Male   Female Female Male   Male
    Levels: Female Male