[R] Variable Generation

This post covers how to generate variables in R Studio.

    1. Rules for variable names

    Variable names can be created by a combination of the following four kinds of characters.
    1) Letters (alphabets, etc.)
    2) Numbers
    3) - (dash)
    4) _ (under-bar)
    e.g., inc_1, GDP-1990

    Also, R distinguishes uppercase and lowercase letters, so do not confuse yourself by recklessly mixing the two.

    I personally distinguish the level of the variables by putting lowercase letters for individual level variables and uppercase letters for national (or regional) level variables. 
    e.g., 'inc' for individual incomes, 'GDP' for national GDPs


    2. (Non-string) Variable generation

    R uses '<- (assignment operator)' to generate variables.
    Below are the syntax structure and some examples.
    variable name <- value(s)(or function)
    a <- 1
    weight <- 50
    x_m <- mean(x)
    
    ('mean' is a function that computes the average of a variable)

    There are some functions that help including multiple values.

    1) c()

    c() function lets you include multiple values at once which are separated by ','.

    Also, by putting ':' in the parentheses with two numbers side of it, you can create a variable with consecutive numbers increasing by 1.

    #c() function
    var1 <- c(1, 3, 12, 68, 121)
    var2 <- c(1:5)
    var1
    var2
    
    #Console window
    > var1
    [1]   1   3  12  68 121
    > var2
    [1] 1 2 3 4 5
    

    2) seq()

    seq() function does the same job as c(a:b), but with a starting number, ',' , and the last number.
    Also, with 'by' parameter, you can set the intervals of the consecutive numbers.
    #seq() function
    var3 <- seq(1,5)
    var4 <- seq(1,10,by=2)
    var3
    var4
    
    #Console window
    > var3
    [1] 1 2 3 4 5
    > var4
    [1] 1 3 5 7 9
    

    3. String variable generation


    When inputting strings or characters as values in a variable, the syntax must include quotation marks (" ").

    c() function also works for the string variable generation.

    #string variable generation
    str1 <- "apple"
    str2 <- "Apple_Banana_Carrot!"
    str3 <- c("a", "b", "c")
    str4 <- c("Apple", "Banana", "Carrot")
    str1
    str2
    str3
    str4
    
    #Console window
    > str1
    [1] "apple"
    > str2
    [1] "Apple_Banana_Carrot!"
    > str3
    [1] "a" "b" "c"
    > str4
    [1] "Apple"  "Banana" "Carrot"
    

    Post a Comment

    0 Comments