# R語言變量

`var_name2.` 有效 由字母，數字，點和下劃線組成
`var_name%` 無效 含有字符`「%」`因此無效。只允許點(`.`)和下劃線(`_`)組成。
`2var_name` 無效 以數字開頭，因此無效。
`.var_name`, `var.name` 有效 可以以點(`.`)開頭，但點(`.`)後面不應是數字。
`.2var_name` 無效 以點(`.`)但後跟一個數字使其無效。
`_var_name` 無效 以下劃(`_`)開始因此無效。

## 變量賦值

``````# Assignment using equal operator.
var.1 = c(0,1,2,3)

# Assignment using leftward operator.
var.2 <- c("learn","R")

# Assignment using rightward operator.
c(TRUE,1) -> var.3

print(var.1)
cat ("var.1 is ", var.1 ,"\n")
cat ("var.2 is ", var.2 ,"\n")
cat ("var.3 is ", var.3 ,"\n")``````

``````> print(var.1)
[1] 0 1 2 3
> cat ("var.1 is ", var.1 ,"\n")
var.1 is  0 1 2 3
> cat ("var.2 is ", var.2 ,"\n")
var.2 is  learn R
> cat ("var.3 is ", var.3 ,"\n")
var.3 is  1 1``````

## 變量的數據類型

``````var_x <- "Hello"
cat("The class of var_x is ",class(var_x),"\n")

var_x <- 34.5
cat("  Now the class of var_x is ",class(var_x),"\n")

var_x <- 27L
cat("   Next the class of var_x becomes ",class(var_x),"\n")``````

``````> var_x <- "Hello"
> cat("The class of var_x is ",class(var_x),"\n")
The class of var_x is  character
>
> var_x <- 34.5
> cat("  Now the class of var_x is ",class(var_x),"\n")
Now the class of var_x is  numeric
>
> var_x <- 27L
> cat("   Next the class of var_x becomes ",class(var_x),"\n")
Next the class of var_x becomes  integer
>``````

## 查找變量

``print(ls());``

``````> print(ls());
[1] "string" "var.1"  "var.2"  "var.3"  "var_x"``````

`ls()`函數可以使用模式來匹配變量名。

``````# List the variables starting with the pattern "var".
print(ls(pattern = "var"))``````

``````> print(ls(pattern = "var"))
[1] "var.1" "var.2" "var.3" "var_x"``````

``print(ls(all.names = TRUE));``

``````> print(ls(all.names = TRUE));
[1] ".var_no" ".var1"   "string"  "var.1"   "var.2"   "var.3"   "var_x"
>``````

## 刪除變量

``````rm(var.3)
print(var.3)``````

``````> rm(var.3)
> print(var.3)
Error in print(var.3) : 找不到對象'var.3'``````

``````rm(list = ls())
print(ls())``````

``````> rm(list = ls())
> print(ls())
character(0)``````