Previous: Classes of Variables | Up: Classes of Variables | Next: Recoding Variables |
For all types of variable (vectors), you may use the c() command to ``concatenate'' elements into a vector, the : operator to generate a sequence of integer values, the seq() command to generate a sequence of non-integer values, or the rep() function to repeat a value to a specified length. In addition, you may use the <- operator to save variables (or any other objects) to the workspace. For example:
> logic <- c(TRUE, FALSE, TRUE, TRUE, TRUE) # Creates `logic' (5 T/F values). > var1 <- 10:20 # All integers between 10 and 20. > var2 <- seq(from = 5, to = 10, by = 0.5) # Sequence from 5 to 10 by # intervals of 0.5. > var3 <- rep(NA, length = 20) # 20 `NA' values. > var4 <- c(rep(1, 15), rep(0, 15)) # 15 `1's followed by 15 `0's.For the seq() command, you may alternatively specify length instead of by to create a variable with a specific number (denoted by the length argument) of evenly spaced elements.
> var3 <- log(var2) - 2*var1 # Create `var3' using math operations.Inf (infinity), -Inf (negative infinity), NA (missing value), and NaN (not a number) are special numeric values on which most math operations will fail. (Logical operations will work, however.) Use as.numeric() to transform variables into numeric variables. Integers are a special class of numeric variable.
> var3 <- var1 < var2 > var3 <- var1 == var2create 2#2 TRUE/FALSE observations such that the 4#4 th observation in var3 evaluates whether the logical statement is true for the 4#4 th value of var1 with respect to the 4#4 th value of var2. Logical variables should usually be converted to integer values prior to analysis; use the as.integer() command.