一些函数

table()函数

table()的输出可以看成是一个带名字的数字向量。可以用names()和as.numeric()分别得到名称和频数:

> x <- sample(c("a", "b", "c"), 100, replace=TRUE)
> names(table(x))
[1] "a" "b" "c"
> as.numeric(table(x))
[1] 42 25 33

或者,可以直接把输出结果转化为数据框,as.data.frame():

> as.data.frame(table(x))
  x Freq
1 a   42
2 b   25
3 c   33

assign()函数

为一个变量名称赋值。 Assign a Value to a Name Assign a value to a name in an environment.

用法

assign(x, value, pos = -1, envir = as.environment(pos),
inherits = FALSE, immediate = TRUE)

参数

  • x:变量名称,字符串类型,x只能是一个字符串,如果为字符串向量,则会使用向量的第一个元素,并给出warning;
    • a variable name, given as a character string. No coercion is done, and the first element of a character vector of length greater than one will be used, with a warning.
  • value:赋给x的变量值;
  • pos:where to do the assignment. By default, assigns into the current environment.
  • envir:the environment to use.
  • inherits:should the enclosing frames of the environment be inspected?
  • immediate:an ignored compatibility feature.

get()函数/mget()函数

根据变量名称获取该变量的值。 Return the Value of a Named Object; Search by name for an object (get) or zero or more objects (mget)

用法

get(x, pos = -1, envir = as.environment(pos), mode = "any",
inherits = TRUE)
mget(x, envir = as.environment(-1), mode = "any", 
ifnotfound, inherits = FALSE)

参数

  • x:
    • For get, an object name (given as a character string).
    • For mget, a character vector of object names.
  • pos, envir:where to look for the object ; if omitted search as if the name of the object appeared unquoted in an expression.
  • mode: the mode or type of object sought;
  • inherits: should the enclosing frames of the environment be searched?
  • ifnotfound: For mget, a list of values to be used if the item is not found: it will be coerced to a list if necessary.
> for(i in 1 : 6){
+   assign(paste('var', i, sep = ''), i)
+   print(get(paste('var', i, sep = '')))  
+ }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
[1] 6

attach()/detach()

函数attach()可将数据框添加到R的搜索路径中。R在遇到一个变量名以后,将检查搜索路径中的数据框,以定位到这个变量; detach()去除一个数据框的绑定。

函数 search 显示当前的搜索路径。它可以用来跟踪已经被绑定或者绑定去除的列表和数据框(以及包)。

results matching ""

    No results matching ""