官术网_书友最值得收藏!

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

主站蜘蛛池模板: 昌邑市| 六盘水市| 新巴尔虎右旗| 浪卡子县| 阳东县| 贵州省| 从江县| 孟州市| 萍乡市| 鞍山市| 靖远县| 潜江市| 南开区| 张家界市| 瑞昌市| 博兴县| 鹰潭市| 南涧| 江西省| 尼玛县| 建湖县| 邻水| 达拉特旗| 获嘉县| 曲靖市| 迭部县| 仪征市| 平顶山市| 施甸县| 西藏| 蓝山县| 德格县| 图木舒克市| 沂水县| 桐庐县| 丹棱县| 炎陵县| 新密市| 靖安县| 宜阳县| 乌兰浩特市|