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

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

主站蜘蛛池模板: 灌阳县| 淳安县| 礼泉县| 泸定县| 崇文区| 伊金霍洛旗| 尚志市| 库车县| 阳谷县| 开封市| 上犹县| 绵竹市| 潮州市| 通道| 会同县| 雷波县| 盐池县| 玉山县| 望奎县| 广灵县| 平凉市| 民乐县| 政和县| 赤城县| 南木林县| 开平市| 天气| 满洲里市| 开封市| 岱山县| 朝阳市| 镇安县| 林西县| 黑山县| 姜堰市| 盐津县| 兰考县| 花莲市| 澄城县| 渝北区| 修文县|